leetcode387 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.
Subscribe to see which companies asked this question
class Solution {
public:
int firstUniqChar(string s) {
map<char, set<int> > c_index;
set<int> index_queue;
if (s.size() == 0)
{
return -1;
}
for (int i = 0; i < s.size(); ++i)
{
c_index[s[i]].insert(i);
}
map<char, set<int> >::iterator it = c_index.begin();
for (; it != c_index.end(); ++it)
{
if (it->second.size() == 1)
{
index_queue.insert(*(it->second.begin()));
}
}
return index_queue.size() > 0 ? *index_queue.begin() : -1;
}
};
我这个方法跑完一看,耗时接近1秒,,,,,有点爆炸,,后来看了讨论区的内容,发现了类似桶排序的方法,还是很巧妙的,用下标代表实际的字符值,实际的值代表字符出现的次数。
class Solution {
public:
int firstUniqChar(string s) {
vector<int> v (26,0);
for ( int i = 0; i < s.length(); ++i )
{
v[s[i]-'a']++;
}
for ( int i = 0; i < s.length(); ++i )
{
if ( v[s[i]-'a'] == 1 )
{
return i;
}
}
return -1;
}
};
我后来想了一下,我没想到这方法的原因是没注意这句话