C++中居然有和python字典一样的东西
unordered_map(无序)、map (有序)
先计算所有字母的频数,用unordered_map映射存储;接着,遍历str,找出unordered_map中value为1的key
class Solution {
public:
int FirstNotRepeatingChar(string str) {
if(str.size() == 0) return -1;
unordered_map<char, int> countMap;
for(int i = 0;i < str.size();i++){
countMap[str[i]]++;
}
int pos = -1;
for(int i = 0;i < str.size();i++){
if(countMap[str[i]] == 1){
pos = i;
break;
}
}
return pos;
}
};
python实现:
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
if s == "":
return -1
count = {}
for i in s:
if i in count:
count[i] += 1;
else:
count[i] = 1
for index,item in enumerate(s):#取s的下标和值
if count[item] == 1:
return index
版权声明:本文为qq_27855219原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。