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