- 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.
我的做法:
class Solution {
public:
int firstUniqChar(string s) {
map<char, int> maps;
char target;
int min=-1;
for (char a : s)
{
maps[a]++;
}
for (map<char, int>::iterator iter = maps.begin(); iter != maps.end(); iter++)
{
if (iter->second == 1)
{
target = iter->first;
if (min == -1)
min = s.find(target);
if (min > s.find(target))
{
min = s.find(target);
}
}
}
return min;
}
};
太慢了,太冗余,后来发现别人的做法跟我刚开始的想法相似,不过他解决了查询过程中,查的不是按照字母表先后顺序,而是按照字母在字符串中顺序的问题。
别人的做法:
class Solution {
public:
int firstUniqChar(string s) {
int m[26] = {0};
for (char a : s) m[a - 'a']++;
for (int i = 0; i < s.length(); i++) if (m[s[i] - 'a'] == 1) return i;
return -1;
}
};