原题
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
Reference Answer
思路分析
直接遍历字符串,用python dict进行次数统计,最后返回目标值对应最小的index。
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
temp_dict = {}
temp_index = {}
for index, value in enumerate(s):
if value not in temp_dict:
temp_dict[value] = 1
temp_index[value] = index
else:
temp_dict[value] += 1
print(temp_dict)
print(temp_index)
res = len(s)
for key, value in temp_dict.items():
if value == 1:
res = min(res, temp_index[key])
if res == len(s):
return -1
else:
return res
这道题时间复杂度、空间复杂度到大约是少不了了,提供一个 C++ 版本:
class Solution {
public:
int FirstNotRepeatingChar(string str) {
int length = str.size();
if(length == 0){
return -1;
}
map<char, int> item;
for(int i = 0; i < length; i++){
item[str[i]]++;
}
for (int i =0; i < length; i++){
if(item[str[i]] == 1){
return i;
}
}
return -1;
}
};
补充一个简化版:
import collections
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
temp_res = list(filter(lambda c: s.count(c) == 1, s))
res = s.index(temp_res[0]) if temp_res else -1
return res
Note
需要注意的一点是关于python中对dict进行按照key排序以及按照value排序的适用方法。
- 按照value排序:
res = sorted(temp_res.items(), key = lambda temp_res:temp_res[1])
- 按照key排序:
res = sorted(temp_res.items(), key = lambda temp_res:temp_res[0])