题目描述:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 - 1。
案例 :
s = “leetcode”
返回 0
s = “loveleetcode”,
返回 2.
思路:
统计每个字符出现了多少次:字符作为计数数组的下标,遇到相同字符,加1,遍历每个字符,如果出现一次,则找到
class Solution {
public:
int firstUniqChar(string s) {
int count[256] = { 0 };
//每一个字符出现了几次
for (size_t i = 0; i<s.size(); i++)
{
count[s[i]]++;
}
//出现一次的
for (size_t i = 0; i<s.size(); i++)
{
if (1 == count[s[i]])
{
return i;
}
}
return -1;
}
};
int main()
{
Solution s;
cout << s.firstUniqChar("loveleetcode") << endl;//2
return 0;
}
leetcode(力扣)链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/submissions/