题目:
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.
大意:输出字符串中第一个只出现了一次的字符的下标
思路:
1.建立一个长度为26的数组,遍历一次字符串记录各字符出现次数。再遍历一遍,输出第一个出现次数为0的字符的下标。
2.思路同理,用哈希表建立每个字符和其出现次数的映射,然后按顺序遍历字符串,找到第一个出现次数为1的字符,返回其位置。
代码:
思路1:
class Solution {
public:
int firstUniqChar(string s) {
int sl[26];
int res = -1;
for (int j = 0; j < 26; j++)
{
sl[j] = 0;
}
for (int i = 0; i < s.length(); i++)
{
sl[int(s[i]) - 97]++;
}
for (int i = 0; i < s.length(); i++)
{
if (sl[int(s[i])-97]==1)
{
res = i;
break;
}
}
return res;
}
};
思路2:
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, int> m;
for (char c : s) ++m[c];
for (int i = 0; i < s.size(); ++i) {
if (m[s[i]] == 1) return i;
}
return -1;
}
};
思路2代码出处: http://www.cnblogs.com/grandyang/p/5802109.html