classSolution:deffirstUniqChar(self, s:str)->int:
frequency = collections.Counter(s)for i, ch inenumerate(s):if frequency[ch]==1:return i
哈希存索引:
classSolution:deffirstUniqChar(self, s):
d ={}
length =len(s)for i inrange(length):if s[i]notin d:
d[s[i]]= i
else:
d[s[i]]= length +1
ret =min(d.values())return-1if ret > length else ret
实现Trie
什么是trie?Trie,又称前缀树或字典树,是一棵有根树,其每个节点包含以下字段:
代码实现:
classTrie:def__init__(self):
self.children =[None]*26
self.isEnd =Falsedefinsert(self, word:str)->None:
nownode = self
for ch in word:
ch =ord(ch)-ord('a')ifnot nownode.children[ch]:
nownode.children[ch]= Trie()
nownode = nownode.children[ch]
nownode.isEnd =TruedefsearchPrefix(self, prefix:str)->"Trie":
nownode = self
for ch in prefix:
ch =ord(ch)-ord("a")ifnot nownode.children[ch]:returnNone
nownode = nownode.children[ch]return nownode
defsearch(self, word:str)->bool:
tree = self.search(word)return tree isnotNoneand tree.isEnd
defstartsWith(self, prefix:str)->bool:return self.searchPrefix(prefix)isnotNone