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.
思路
首先统计每个字符的出现次数,然后遍历一次原字符串,找出第一个出现一次的字符即可。
用c语言的写法类似于389题,直接自己定义bitmap就好了
这里就用C++ 的map来写一遍
代码(C++)
class Solution {
public:
int firstUniqChar(string s) {
if(s.empty())
return -1;
int len = s.size();
map<char, int> map_str;
for (int i = 0; i < len; i++)
{
map_str[s[i]]++;
}
for (int i = 0; i < len; i++)
{
if (1 == map_str[s[i]])
return i;
}
return -1;
}
};
代码(python)
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
dic = collections.Counter(s)
res = -1
for index, ch in enumerate(s):
if dic[ch] == 1:
res = index
break
return res
学习总结
这个python的代码我是学习了这里,我自己也写了一套python的代码,没这个简洁,就不贴了。
关于collections.Counter()前面这里已经讲过了
enumerate()学习:
enumerate函数用于遍历序列中的元素以及它们的下标,在python中enumerate的用法多用于在for循环中得到计数。
例1:
import string
s = string.ascii_lowercase
e = enumerate(s)
print s
print list(e)
输出:
abcdefghij
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')]
例2:
i = 0
seq = ['one', 'two', 'three']
for element in seq:
print i, seq[i]
i += 1
print '==========='
i = 0
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
print i, seq[i]
输出:
0 one
1 two
2 three
===========
0 one
1 two
2 three
1616




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



