劍指offer 第一個只出現一次的字元 python
阿新 • • 發佈:2018-12-26
題目描述
在一個字串(0<=字串長度<=10000,全部由字母組成)中找到第一個只出現一次的字元,並返回它的位置, 如果沒有則返回 -1(需要區分大小寫).
樣例
輸入google
輸出4
想法:
第一回遍歷一次生成字典,第二回遍歷找到值對應的index
class Solution:
def FirstNotRepeatingChar(self, s):
c = {}
for i in s:
if i in c:
c[i] += 1
else :
c[i] = 1
for index, i in enumerate(s):
if c[i] is 1:
return index
return -1
# 一行版本
# 找到了一個Bug 如果無出現一次的數 則報錯
def FirstNotRepeatingChar_onerow(self, s):
return s.index(list(filter(lambda x: s.count(x) == 1, s))[0]) if s else -1
最後
刷過的LeetCode或劍指offer原始碼放在Github上了,希望喜歡或者覺得有用的朋友點個star或者follow。
有任何問題可以在下面評論或者通過私信或聯絡方式找我。
聯絡方式
QQ:791034063
Wechat:liuyuhang791034063
CSDN:https://blog.csdn.net/Sun_White_Boy
Github:https://github.com/liuyuhang791034063