LeetCode First Unique Character in a String Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1. Examples:
s = "leetcode" return 0. s = "loveleetcode", return 2.Note: You may assume the string contain only lowercase letters.
本题要求找出字符串中第一个没有重复出现的字符。简单题,先对所有字符hash,找出字符和频率的对应关系,然后遍历字符串,返回第一个频率为1的字符。完整代码如下: [cpp] class Solution { public: int firstUniqChar(string s) { unordered_map<char, int> hash; for (int i = 0; i < s.size(); ++i) { ++hash[s[i]]; } for (int i = 0; i < s.size(); ++i) { if (hash[s[i]] == 1)return i; } return -1; } }; [/cpp] 本代码提交AC,用时92MS。]]>