16天:
399,除法求值:
跟算有效括号一样,用一个字典记下来,然后找对应就行
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
g = defaultdict(dict)
for (a,b), v in zip(equations, values): g[a][b], g[b][a] = v, 1/v
for k in g:
for i in g:
for j in g:
if k in g[i] and j in g[k]:
g[i][j] = g[i][k] * g[k][j]
return [g[a][b] if a in g and b in g[a] else -1.0 for a, b in queries]
最大收获是那个 g = defaultdict(dict),defaultdict 真是个好东西啊。
第17天:
438,找到字符串中所有字母异位词
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
n, m = len(s), len(p)
if m > n:
return []
cnt = collections.Counter(p)
need = m
res = []
for right in range(n):
ch = s[right]
if ch in cnt:
if cnt[ch] > 0:
need -= 1
cnt[ch] -= 1
left = right - m
if left >= 0:
ch = s[left]
if ch in cnt:
if cnt[ch] >= 0:
need += 1
cnt[ch] += 1
if need == 0:
res.append(right-m+1)
return res
关键该学的东西是这个:cnt = collections.Counter(p),很重要,他记下了p里面的词和它的次数字典,然后就是一个滑动窗口,不停的滑动然后维护那个cnt来决定是否结束,很有趣。
class Solution:
def decodeString(self, s: str) -> str:
stack = []
num = 0
res = ''
for c in s:
if c.isdigit():
num = num * 10 + int(c)
elif c == '[':
stack.append((res, num))
res, num = '', 0
elif c == ']':
top = stack.pop()
res = top[0] + res * top[1]
else:
res += c
return res
这个很简单,就是维护一个栈然后不停的遍历弹出来就是了,跟有效括号那个是一个意思,只是每次把过去的状态放进去,现在的状态是放在res里面这点记得,还有那个num是为了记录非个位数的。
第18天:
这是看了那个数据结构课后想做的一个实现前缀树,前缀树就是每个节点记录一个字符,然后把一个个字符放进去的一个数据结构,这样通过遍历查找字符可以快速的查找出前缀和某个词,都是工程实现,不难。
class Node(object):
def __init__(self):
self.children = collections.defaultdict(Node)
self.isword = False
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word: str) -> None:
current = self.root
for w in word:
current = current.children[w]
current.isword = True
def search(self, word: str) -> bool:
current = self.root
for w in word:
current = current.children.get(w)
if current == None:
return False
return current.isword
def startsWith(self, prefix: str) -> bool:
current = self.root
for w in prefix:
current = current.children.get(w)
if current == None:
return False
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
dp = [True] + [False]*n
for i in range(1, n+1):
for word in wordDict:
if dp[i - len(word)]:
if word == s[i-len(word): i]:
dp[i] = True
return dp[-1]
经典动态规划,初始状态只要0是true,然后二维,一个个点的遍历,然后每个词遍历过去,看词长度前的那个状态是否符合词,动态规划很经典的做法。