classSolution: deflengthOfLongestSubstring(self, s: str) -> int: n = len(s) if n < 2: return n
left = right = max_len = 0 while left <= right < n: if s[right] in s[left:right]: while left <= right and s[right] in s[left:right]: left += 1 right += 1 max_len = max(max_len, right - left)
classSolution: defreverse(self, x: int) -> int: s = str(x)[::-1] res = -int(s[:-1]) if x < 0else int(s) return res if-2**31 <= res <= 2**31 - 1else0
当然这是一种做法 还有一种做法就是数学方法来解
注意这里去绝对值是因为python//取余数的话123//10=13
1 2 3 4 5 6 7 8 9 10 11
classSolution: defreverse(self, x: int) -> int: res, y = 0, abs(x) out = 1<<31if x > 0else (1<<31)-1 while y != 0: pop = y % 10 res = res * 10 + pop if res > out: return0 y //= 10 return res if x > 0else -res
classSolution: defmyAtoi(self, str: str) -> int: s = str.lstrip() ifnot s: return0 flag = True if s[0] == '-': flag = False s = s[1:] elif s[0] == '+': s = s[1:] res = i = 0 bo = (1 << 31) - 1if flag else1 << 31 while i < len(s) and s[i].isdigit(): res = res * 10 + int(s[i]) if res > bo: return (1 << 31) - 1if flag else-1 << 31 i += 1 return res if flag else -res
4. 盛最多水的容器
给定 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在 坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的 两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
classSolution: defsearchInsert(self, nums: List[int], target: int) -> int: ifnot nums: return0 n = len(nums) for i in range(n): if nums[i] >= target: return i return n
classSolution: defcanJump(self, nums: List[int]) -> bool: n = len(nums) left_index = n - 1 for i in reversed(range(n - 1)): if i + nums[i] >= left_index: left_index = i return left_index == 0
还有种思路 最远能到达的位置大于终点即可
max_i >= i保证能到达i位置 防止[3,2,1,0,4]
1 2 3 4 5 6 7 8 9 10
classSolution: defcanJump(self, nums: List[int]) -> bool: n = len(nums) max_i = 0 for i, jump in enumerate(nums): if max_i >= i and i + jump > max_i: max_i = i + jump if max_i >= n - 1: returnTrue returnFalse
classSolution: defrotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n = len(matrix) for i in range(n): left, right = 0, n - 1 while left < right: matrix[i][left], matrix[i][right] = matrix[i][right], matrix[i][left] left += 1 right -= 1 for i in range(n): for j in range(n): if i + j < n - 1: matrix[i][j], matrix[n - 1 - j][n - 1 - i] = matrix[n - 1 - j][n - 1 - i], matrix[i][j]
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
classSolution: deflevelOrder(self, root: TreeNode) -> List[List[int]]: res = [] ifnot root: return res level = 0 deque = [root] while deque: res.append([]) n = len(deque) for i in range(n): node = deque.pop(0) res[level].append(node.val) if node.left: deque.append(node.left) if node.right: deque.append(node.right) level += 1 return res
classSolution: defsingleNumber(self, nums: List[int]) -> int: seen_once = seen_twice = 0 for num in nums: # first appearance: # add num to seen_once # don't add to seen_twice because of presence in seen_once # second appearance: # remove num from seen_once # add num to seen_twice # third appearance: # don't add to seen_once because of presence in seen_twice # remove num from seen_twice seen_once = ~seen_twice & (seen_once ^ num) seen_twice = ~seen_once & (seen_twice ^ num)
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defsortList(self, head: ListNode) -> ListNode: # 4, 3, 2, 6, 5, 7, 1 level, h, size, res = 1, head, 0, ListNode(0) res.next = head while h: h = h.next size += 1
level, node = 1, head while level < size: pre, h = res, res.next while h: h1, i = h, level while i and h: h = h.next i -= 1 if i: break# 可能存在第一个都不满 不需要和后面进行排序了例如总长度为6:4, 3, 2, 6, 5, 7的5, 7 h2, i = h, level while i and h: h = h.next i -= 1 l1, l2 = level, level - i # 右部分可能不足level长度 例如 5, 7和1 while l1 and l2: if h1.val < h2.val: pre.next, h1 = h1, h1.next l1 -= 1 else: pre.next, h2 = h2, h2.next l2 -= 1 pre = pre.next pre.next = h1 if l1 else h2 while l1 > 0or l2 > 0: pre = pre.next l1 -= 1 l2 -= 1 pre.next = h
def__init__(self): """ Initialize your data structure here. """ self.trie = {}
definsert(self, word: str) -> None: """ Inserts a word into the trie. """ node = self.trie for w in word: if w notin node: node[w] = {} node = node[w] node['#'] = '#'
defsearch(self, word: str) -> bool: """ Returns if the word is in the trie. """ node = self.trie for w in word: if w notin node: returnFalse node = node[w] if'#'in node: returnTrue else: returnFalse
defstartsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ node = self.trie for w in prefix: if w notin node: returnFalse node = node[w] returnTrue
# 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)
def__init__(self): """ Initialize your data structure here. """ self.root = TrieNode()
definsert(self, word: str) -> None: """ Inserts a word into the trie. """ node = self.root for w in word: if w notin node.child: node.child[w] = TrieNode() node = node.child[w] node.is_end = True
defsearch(self, word: str) -> bool: """ Returns if the word is in the trie. """ node = self.root for w in word: if w notin node.child: returnFalse node = node.child[w] if node.is_end: returnTrue else: returnFalse
defstartsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ node = self.root for w in prefix: if w notin node.child: returnFalse node = node.child[w] returnTrue
# 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)
classTrie: def__init__(self, word_list): """ Initialize your data structure here. """ self.root = TrieNode() for word in word_list: if word: self.insert(word)
definsert(self, word: str) -> None: """ Inserts a word into the trie. """ node = self.root for w in word: if w notin node.child: node.child[w] = TrieNode() node = node.child[w] node.is_end = True
classSolution: deffindAllConcatenatedWordsInADict(self, words): t = Trie(words) res = []
defdfs(node, i, w, has_cut): if i == len(w): return node.is_end and has_cut if node.is_end: if dfs(t.root, i, w, True): returnTrue
if w[i] notin node.child: returnFalse else: return dfs(node.child[w[i]], i + 1, w, has_cut)
for w in words: if dfs(t.root, 0, w, False): res.append(w) return res
classSolution: deffindMinStep(self, board: str, hand: str) -> int: # 'RBYYBBBRRB' => 'RBYYRRB' defclear(b): i = 0 while i < len(b): j = i while j < len(b) and b[j] == b[i]: j += 1 if j - i >= 3: b = b[:i] + b[j:] i = 0 else: i += 1 return b
defdfs(b, h): n = len(b) if n == 0: return0 max_ball, i, j = float('inf'), 0, 0 while i < n: while j < n and b[j] == b[i]: j += 1 balls = 3 - (j - i) color = b[i] if h[color] >= balls: nb = clear(b[:j] + color * balls + b[j:]) h[color] -= balls r = dfs(nb, h) # 深度搜索结果不是-1 if r != -1: max_ball = min(max_ball, r + balls) h[color] += balls i = j
return max_ball if max_ball != float('inf') else-1
classSolution: defselfDividingNumbers(self, left: int, right: int) -> List[int]: # 改成字符串 defhelper1(num): for n in list(str(num)): if n == '0'or num % int(n) != 0: returnFalse returnTrue # 数学运算 defhelper2(num): tmp = num while tmp > 0: n = tmp % 10 if n == 0or num % n != 0: returnFalse tmp = tmp // 10 returnTrue
res = [] for num in range(left, right + 1): if helper2(num): res.append(num) return res
classSolution: deflongestPalindrome(self, s: str) -> str: # 两个情况 偶数和奇数 n = len(s) if n <= 1: return s
defhelper(index, is_odd=False): l = index - 1if is_odd else index r = index + 1 while l >= 0and r < n: if s[l] == s[r]: l -= 1 r += 1 else: break return s[l+1:r]
res = '' for i in range(n - 1): odd, even = helper(i, True), helper(i) tmp = odd if len(odd) > len(even) else even if len(res) < len(tmp): res = tmp return res
classSolution: deflongestPalindrome(self, s: str) -> str: n = len(s) if n <= 1: return s
max_len, res = 1, s[0] dp = [[False] * n for _ in range(n)] for i in range(n): dp[i][i] = True
for j in range(1, n): for i in range(j): if s[i] == s[j]: if j - i < 3: dp[i][j] = True else: dp[i][j] = dp[i + 1][j - 1] if dp[i][j]: if j - i + 1 > max_len: max_len = j - i res = s[i:j + 1] return res
classSolution: defcountSubstrings(self, s: str) -> int: n = len(s) if n <= 1: return n res = 0 dp = [[False] * n for _ in range(n)] for i in range(n): dp[i][i] = True res += 1
for j in range(1, n): for i in range(j): if s[i] == s[j]: if j - i < 3: dp[i][j] = True else: dp[i][j] = dp[i + 1][j - 1] if dp[i][j] isTrue: res += 1 return res