051105
题目
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.
我的解题思路
这道题的解题思路跟LeetCode:383. Ransom Note类似,首先可以先建立一个map,遍历字符串,计算每个字符的出现的次数,之后返回第一个只出现一次的字符的位置即可。
class Solution {
public:
int firstUniqChar(string s) {
if(s.length()==0) return -1;
unordered_map<char, int> map(26);
for (int i = 0; i < s.length(); ++i)
++map[s[i]];
for (int i = 0; i < s.length(); ++i){
if(map[s[i]]==1) return i;
}
return -1;
}
};
围观了一波大佬的解法,发现能跟上了,加油!

本文探讨了LeetCode上一道经典题目:寻找字符串中第一个不重复的字符并返回其索引。通过使用unordered_map记录字符频率,实现了高效查找。文章分享了个人解题思路及代码实现,适合算法初学者参考。

482

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



