【英文题目】(学习英语的同时,更能理解题意哟~)
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。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事项:您可以假定该字符串只包含小写字母。
【思路】
对元素进行计数,只保留数量为1的元素,查找其下标最小值即可。
由于字符串只包含小写字母,也可以直接遍历小写字母得到结果,只要计数为0或者超过1个,就continue。
【代码】
python版本
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
d = {}
for si in s:
d[si] = d.get(si, ) +
# 得到所有唯一字符
ls = []
for k,v in d.items():
if v == :
ls.append(k)
# 找到最小下标
if len(ls) == :
return -1
res = s.index(ls[])
for lsi in ls:
res = min(res, s.index(lsi))
return res
C++版本
class Solution {
public:
int firstUniqChar(string s) {
int res = INT_MAX;
int place, place2;
for(int i=; i<; i++){
place = s.find((char)('a'+i), );
if(place >= ){
place2 = s.find((char)('a'+i), place+);
if(place2 >= )
continue;
else
res = min(res, place);
}
}
if(res != INT_MAX)
return res;
return -1;
}
};