LeetCode 387. First Unique Character in a String

时间:2023-03-09 22:08:56
LeetCode 387. First Unique Character in a String

Problem: Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Example:

s = "leetcode"
return 0. s = "loveleetcode",
return 2.

本题的第一想法是开一个字母表计数器,遍历string s中的元素,并利用计数器对每一个字母计数。最后再次遍历s,查找计数为1的字符然后返回其索引。该解法代码如下:

 class Solution {
public:
int firstUniqChar(string s) {
int *alphabet = NULL;
alphabet = new int[]();
for(int i = ; i < s.length(); i++)
{
alphabet[int(s[i] - 'a')]++;
}
for(int i = ; i < s.length(); i++)
{
if(alphabet[int(s[i] - 'a')] == )
{
return i;
}
}
return -; }
};

但是,若string非常长,两次遍历则会带来很大的开销,因此,可以考虑一次遍历,用hash table记录每个字母的次数和索引,其代码如下:

 class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, pair<int,int>> m;
int idx = s.length();
for(int i = ; i < s.length(); i++)
{
m[s[i]].first++;
m[s[i]].second = i;
}
for(auto &p:m)
{
if(p.second.first == )
{
idx = min(idx, p.second.second);
}
}
return idx == s.length()? - : idx;
}
};