Description
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.
分析
题目的意思是:找出一个字符串中第一个不重复的字符。
- 用hash(不排序)表统计词频,然后遍历一遍找到第一个词频为1的字符就行了。
C++实现
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;
}
};
Python实现
class Solution:
def firstUniqChar(self, s: str) -> int:
cmap = defaultdict(int)
for ch in s:
cmap[ch]+=1
for i in range(len(s)):
if cmap[s[i]]==1:
return i
return -1