defcalculate(self, s: str) -> int: # prev_num[prev_op]num, 2+3+4+, 2+3*4+ stack, prev_op, num = [], '+', 0 s += "+" for c in s: if c == "": continue if c.isdigit(): num = num * 10 + int(c) elif c in'+-*/': if prev_op in'*/': prev_num = stack.pop() if prev_op == "*": num = prev_num * num else: num = int(prev_num / num) if prev_op == "-": num = -num stack.append(num) num = 0 prev_op = c returnsum(stack)
第四步判断是否含循环必不可少,要根据题目要求来处理。除非L310 min height明确一定有解,而L269外星人字典就明确可能无解
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
deftopological_sort(self, graph: List[List[int]], n: int) -> List[int]: in_degree = [0] * n for i inrange(len(graph)): for node in graph[i]: in_degree[node] += 1
start_nodes = [i for i inrange(len(in_degree)) if in_degree[i] == 0] queue, res = deque(start_nodes), [] while queue: node = queue.popleft() res.append(node) for neighbor in graph[node]: in_degree[neighbor] -= 1 if in_degree[neighbor] == 0: queue.append(neighbor) return res iflen(res) == n elseNone
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