问题:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。
输入:一个字符串(仅包含英文小写字母)
输出:第一个不重复的字符索引(不存在则返回-1)
思路:
遍历一遍字符串,利用hash表存储,每个字符为key时,value加1。
然后,正序遍历一遍字符串,如果value为1,则返回其索引。
(或者,遍历一遍hash表,如下第一个代码,判断是否为不重复的数字,比较得到最小的索引。)
上述两个方法的运行时间和内存占用差不多,因此,猜测时间主要消耗在hash表的建立和查询上。
代码:
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, pair<int,int>> map;
int i=0;
int index=s.size();
while(s[i]!='\0')
{
// map[s[i]].first++;
map[s[i]].first++;
if(map[s[i]].first==1)
map[s[i]].second=i;
i++;
}
for(auto m:map)
{
if(m.second.first==1)
index = min(index, m.second.second);
}
return s.size()==index?-1:index; // 对于“cc”很必要
}
};
别人的优雅代码:
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, int> m;
for (auto &c : s) {
m[c]++;
}
for (int i = 0; i < s.size(); i++) {
if (m[s[i]] == 1) return i;
}
return -1;
}
};
别人优雅代码:
class Solution {
public:
int firstUniqChar(string s) {
int list[256] = {0};
for(auto i: s)
list[i] ++;
for(int i=0; i<s.length();i++)
if(list[s[i]]==1) return i;
return -1;
}
};
三者时间复杂度,第三个为前两者的一半,非常好的思想是char变换为int型,作为数组的索引。
复杂度分析:由于不知道建立hash表,查询的时间复杂度,时间复杂度暂定O(n),