[LeetCode]387. First Unique Character in a String
题目描述
思路
遍历,对于每个字符,找到第一个相同的字符就终止
找到第一个满足条件的字符,终止循环
update1
用map计数,然后遍历字符串,当字符满足个数为1时,返回。若没有,返回-1
代码
class Solution {
public:
int firstUniqChar(string s) {
int len = s.size();
int result = -1;
for (int i = 0; i < len; ++i){
bool flag = true;
for (int j = 0; j < len; ++j){
if (s[i] == s[j] && i != j) {
flag = false;
break;
}
}
if (flag) {
result = i;
break;
}
}
return result;
}
};
update1
class Solution {
public:
int firstUniqChar(string s) {
int len = s.size();
unordered_map<char, int> charMap;
for (auto &p : s){
charMap[p]++;
}
for (int i = 0; i < len; i++){
if (charMap[s[i]] == 1){
return i;
}
}
return -1;
}
};
本文介绍了解决LeetCode 387题“字符串中的第一个唯一字符”的两种方法:一种是通过遍历字符串来查找唯一字符;另一种是利用哈希映射(map)进行字符计数,再遍历字符串找出第一个出现一次的字符。最终返回该字符的位置或-1。
524

被折叠的 条评论
为什么被折叠?



