題目描述
在一個字符串(0<=字符串長度<=10000,全部由字母組成)中找到第一個只出現一次的字符,並返回它的位置, 如果沒有則返回 -1(需要區分大小寫).
注意:因爲題目要求返回字符(或者字符出現的位置),一次第二次遍歷是也是字符串s,而不是哈希表
#方法一:利用數組自己建立個哈希表
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if s==' ':
return -1
hashtable=[0]*256
for i in s:
hashtable[ord(i)] += 1
for i in s:
if hashtable[ord(i)]==1:
return s.index(i)
return -1
#方法二:利用python自帶的字典
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if s==' ':
return -1
d=dict()
#第一次遍歷字符串,將每個字符的次數存入字典
for i in s:
d[i]=d.get(i,0)+1
#第二次遍歷字符串,檢查每個字符出現的次數
for i in s:
if d[i]==1: #O(1)
return s.index(i)
return -1