劍指offer-(第一個只出現一次的字元)
阿新 • • 發佈:2019-01-23
題目描述
在一個字串(0<=字串長度<=10000,全部由字母組成)
中找到第一個只出現一次的字元,並返回它的位置,
如果沒有則返回 -1(需要區分大小寫).
解題思路:
1、採用字典儲存字元和出現的次數
2、將字典存入list中
3、遍歷列表找value值中為1的在原字串中找到其索引
程式碼實現
class Solution:
def FirstNotRepeatingChar(self,s):
'''
1、字典儲存字元和出現次數(字元:次數)
2、將字典儲存到列表中,遍歷列表找出第一個次數為1的字元輸出
:param string:
:return:
'''
dict = {}
for str in s:
if str not in dict.keys():
dict[str] = 1
else:
dict[str] += 1
list = [item for item in dict.items()]
for tuple in list:
if tuple[1] == 1:
index = s.index(tuple[0 ])
return index
break
return -1
if __name__ =='__main__':
c = Solution()
print(c.FirstNotRepeatingChar('NXWtnzyoHoBhUJaPauJaAitLWNMlkKwDYbbigdMMaYfkVPhGZcrEwp'))