deftwo_pointers(self, nums): for i inrange(len(nums)): <calculate condition such as char_to_count> while <meets condition>: res = min(res, i - left + 1) <anti-calculate condition such as char_to_count> left += 1 return <result>
求最长串
Python代码:
1 2 3 4 5 6 7 8
deftwo_pointers(self, nums): for i inrange(len(nums)): <calculate condition such as char_to_count> while <does not meet condition>: <anti-calculate condition such as char_to_count> left += 1 res = max(res, i - left + 1) return <result>
definsert(self, word: str) -> None: it = self.head for i inrange(len(word)): # if word[i] not in it.children: #it.children[word[i]] = TrieNode() it = it.children[word[i]] it.is_end = True
defsearch(self, word: str) -> bool: it = self.head for i inrange(len(word)): if word[i] notin it.children: returnFalse it = it.children[word[i]] return it.is_end
defstartsWith(self, prefix: str) -> bool: it = self.head for i inrange(len(prefix)): if prefix[i] notin it.children: returnFalse it = it.children[prefix[i]] returnTrue
definsert(self, word: str) -> None: ifnot word: return it = self.head for i inrange(len(word)): # if word[i] not in it.children: # it.children[word[i]] = TrieNode() it = it.children[word[i]] if i == len(word) - 1: it.is_end = True
defsearch(self, word: str) -> bool: ifnot word: returnFalse it = self.head for i inrange(len(word)): if word[i] notin it.children: returnFalse it = it.children[word[i]] if i == len(word) - 1and it.is_end: returnTrue returnFalse
defstartsWith(self, prefix: str) -> bool: ifnot prefix: returnFalse it = self.head for i inrange(len(prefix)): if prefix[i] notin it.children: returnFalse it = it.children[prefix[i]] if i == len(prefix) - 1: returnTrue returnFalse
第四步判断是否含循环必不可少,要根据题目要求来处理。除非L310 min height明确一定有解,而L269外星人字典就明确可能无解
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
deftopological_sort(self, graph: List[List[int]], n: int) -> List[int]: in_degree = [0] * n for i inrange(len(graph)): for j inrange(len(graph[i])): in_degree[graph[i][j]] += 1
start_nodes = [i for i inrange(len(in_degree)) if in_degree[i] == 0] queue, res = deque(start_nodes), []
while queue: root = queue.popleft() res.append(root) for i in graph[root]: in_degree[i] -= 1 if in_degree[i] == 0: queue.append(i) return res iflen(res) == n elseNone