1. 實現 Trie (前綴樹)
208. implement-trie-prefix-tree
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
用dict嵌套構造字典樹
如果一個節點包含空的子節點, 說明其可以作爲終止符
"""
self.tree = {}
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
node = self.tree
for char in word:
if char not in node:
node[char] = {}
node = node[char]
node[None] = None
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.tree
for char in word:
if char not in node:
return False
node = node[char]
return True if None in node else False
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.tree
for char in prefix:
if char not in node:
return False
node = node[char]
return True
2. 迴文子串
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
笨辦法
暴力搜索所有可能的子串, 逐個判斷是否是迴文串
聰明解法
中心擴展法
長度爲N的字符串的迴文子串中心有2N-1個,
比如 abc 的迴文子串可能的中心有a, b, c, ab之間, bc之間
對每個中心, 向外擴展, 統計其所有的迴文子串數量
馬拉車算法, 對中心擴展法的改進, 暫不做掌握
"""
cnt = 0
for center in range(2*len(s)-1):
if center % 2 == 0: # 偶數, 中心在字母上
left, right = center / 2, center / 2
else: # 奇數, 中心在字母中間
left, right = center // 2, center // 2 + 1
while left <= right and left >= 0 and right < len(s) and s[left] == s[right]: # 向外擴展
cnt += 1
left -= 1
right += 1
return cnt