From 0f5b0250a3e55324fa68e8d96bcdf700663950fb Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 4 May 2023 21:49:12 -0500 Subject: [PATCH 01/35] =?UTF-8?q?Update=200110.=E5=B9=B3=E8=A1=A1=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...241\344\272\214\345\217\211\346\240\221.md" | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git "a/problems/0110.\345\271\263\350\241\241\344\272\214\345\217\211\346\240\221.md" "b/problems/0110.\345\271\263\350\241\241\344\272\214\345\217\211\346\240\221.md" index 804c95eb27..a3bc77fb11 100644 --- "a/problems/0110.\345\271\263\350\241\241\344\272\214\345\217\211\346\240\221.md" +++ "b/problems/0110.\345\271\263\350\241\241\344\272\214\345\217\211\346\240\221.md" @@ -532,6 +532,24 @@ class Solution: else: return 1 + max(left_height, right_height) ``` +递归法精简版: + +```python +class Solution: + def isBalanced(self, root: TreeNode) -> bool: + return self.height(root) != -1 + def height(self, node: TreeNode) -> int: + if not node: + return 0 + left = self.height(node.left) + if left == -1: + return -1 + right = self.height(node.right) + if right == -1 or abs(left - right) > 1: + return -1 + return max(left, right) + 1 +``` + 迭代法: From debaa5e4a0cb16a58f226e04b0865ce1b423f122 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 4 May 2023 22:54:49 -0500 Subject: [PATCH 02/35] =?UTF-8?q?Update=200257.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=89=80=E6=9C=89=E8=B7=AF=E5=BE=84.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...00\346\234\211\350\267\257\345\276\204.md" | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git "a/problems/0257.\344\272\214\345\217\211\346\240\221\347\232\204\346\211\200\346\234\211\350\267\257\345\276\204.md" "b/problems/0257.\344\272\214\345\217\211\346\240\221\347\232\204\346\211\200\346\234\211\350\267\257\345\276\204.md" index 8c542ceaa4..c396f4a0fb 100644 --- "a/problems/0257.\344\272\214\345\217\211\346\240\221\347\232\204\346\211\200\346\234\211\350\267\257\345\276\204.md" +++ "b/problems/0257.\344\272\214\345\217\211\346\240\221\347\232\204\346\211\200\346\234\211\350\267\257\345\276\204.md" @@ -468,6 +468,71 @@ class Solution { ``` --- ## Python: + + +递归法+回溯(版本一) +```Python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +import copy +from typing import List, Optional + +class Solution: + def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: + if not root: + return [] + result = [] + self.generate_paths(root, [], result) + return result + + def generate_paths(self, node: TreeNode, path: List[int], result: List[str]) -> None: + path.append(node.val) + if not node.left and not node.right: + result.append('->'.join(map(str, path))) + if node.left: + self.generate_paths(node.left, copy.copy(path), result) + if node.right: + self.generate_paths(node.right, copy.copy(path), result) + path.pop() + + +``` +递归法+回溯(版本二) +```Python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +import copy +from typing import List, Optional + +class Solution: + def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: + if not root: + return [] + result = [] + self.generate_paths(root, [], result) + return result + + def generate_paths(self, node: TreeNode, path: List[int], result: List[str]) -> None: + if not node: + return + path.append(node.val) + if not node.left and not node.right: + result.append('->'.join(map(str, path))) + else: + self.generate_paths(node.left, copy.copy(path), result) + self.generate_paths(node.right, copy.copy(path), result) + path.pop() + +``` + 递归法+隐形回溯 ```Python # Definition for a binary tree node. From 3b0000a280b2e6a5b1bb033556cbc77e793736fb Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 4 May 2023 23:26:06 -0500 Subject: [PATCH 03/35] =?UTF-8?q?Update=200404.=E5=B7=A6=E5=8F=B6=E5=AD=90?= =?UTF-8?q?=E4=B9=8B=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...66\345\255\220\344\271\213\345\222\214.md" | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git "a/problems/0404.\345\267\246\345\217\266\345\255\220\344\271\213\345\222\214.md" "b/problems/0404.\345\267\246\345\217\266\345\255\220\344\271\213\345\222\214.md" index cf5441c4c4..617978b743 100644 --- "a/problems/0404.\345\267\246\345\217\266\345\255\220\344\271\213\345\222\214.md" +++ "b/problems/0404.\345\267\246\345\217\266\345\255\220\344\271\213\345\222\214.md" @@ -250,19 +250,27 @@ class Solution { **递归后序遍历** ```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: - def sumOfLeftLeaves(self, root: TreeNode) -> int: - if not root: + def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: + if not root: return 0 - left_left_leaves_sum = self.sumOfLeftLeaves(root.left) # 左 - right_left_leaves_sum = self.sumOfLeftLeaves(root.right) # 右 - - cur_left_leaf_val = 0 - if root.left and not root.left.left and not root.left.right: - cur_left_leaf_val = root.left.val + # 检查根节点的左子节点是否为叶节点 + if root.left and not root.left.left and not root.left.right: + left_val = root.left.val + else: + left_val = self.sumOfLeftLeaves(root.left) - return cur_left_leaf_val + left_left_leaves_sum + right_left_leaves_sum # 中 + # 递归地计算右子树左叶节点的和 + right_val = self.sumOfLeftLeaves(root.right) + + return left_val + right_val ``` **迭代** From 4224c17e54e164141ca2f6a08978402ae115fea5 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 19:18:26 -0500 Subject: [PATCH 04/35] =?UTF-8?q?Update=20=E9=9D=A2=E8=AF=95=E9=A2=9802.07?= =?UTF-8?q?.=E9=93=BE=E8=A1=A8=E7=9B=B8=E4=BA=A4.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...76\350\241\250\347\233\270\344\272\244.md" | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git "a/problems/\351\235\242\350\257\225\351\242\23002.07.\351\223\276\350\241\250\347\233\270\344\272\244.md" "b/problems/\351\235\242\350\257\225\351\242\23002.07.\351\223\276\350\241\250\347\233\270\344\272\244.md" index 4bcbd1f920..dda7f2ad00 100644 --- "a/problems/\351\235\242\350\257\225\351\242\23002.07.\351\223\276\350\241\250\347\233\270\344\272\244.md" +++ "b/problems/\351\235\242\350\257\225\351\242\23002.07.\351\223\276\350\241\250\347\233\270\344\272\244.md" @@ -214,7 +214,41 @@ class Solution: return head ``` ```python -(版本三)等比例法 +(版本三)求长度,同时出发 (代码复用 + 精简) +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: + dis = self.getLength(headA) - self.getLength(headB) + + # 通过移动较长的链表,使两链表长度相等 + if dis > 0: + headA = self.moveForward(headA, dis) + else: + headB = self.moveForward(headB, abs(dis)) + + # 将两个头向前移动,直到它们相交 + while headA and headB: + if headA == headB: + return headA + headA = headA.next + headB = headB.next + + return None + + def getLength(self, head: ListNode) -> int: + length = 0 + while head: + length += 1 + head = head.next + return length + + def moveForward(self, head: ListNode, steps: int) -> ListNode: + while steps > 0: + head = head.next + steps -= 1 + return head +``` +```python +(版本四)等比例法 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): From d590d268d717b0241c5d900f70e9356bf3c88903 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 19:50:20 -0500 Subject: [PATCH 05/35] =?UTF-8?q?Update=200242.=E6=9C=89=E6=95=88=E7=9A=84?= =?UTF-8?q?=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...15\345\274\202\344\275\215\350\257\215.md" | 55 ++++++++++++++++--- 1 file changed, 47 insertions(+), 8 deletions(-) diff --git "a/problems/0242.\346\234\211\346\225\210\347\232\204\345\255\227\346\257\215\345\274\202\344\275\215\350\257\215.md" "b/problems/0242.\346\234\211\346\225\210\347\232\204\345\255\227\346\257\215\345\274\202\344\275\215\350\257\215.md" index 1006ea3552..0e5683c794 100644 --- "a/problems/0242.\346\234\211\346\225\210\347\232\204\345\255\227\346\257\215\345\274\202\344\275\215\350\257\215.md" +++ "b/problems/0242.\346\234\211\346\225\210\347\232\204\345\255\227\346\257\215\345\274\202\344\275\215\350\257\215.md" @@ -122,6 +122,21 @@ class Solution { ``` Python: +(版本一) 使用数组 +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + record = [0] * 26 + for i in range(len(s)): + record[ord(s[i]) - ord("a")] += 1 + for i in range(len(t)): + record[ord(t[i]) - ord("a")] -= 1 + for i in range(26): + if record[i] != 0: + return False + return True +``` +(版本二) 使用数组 ```python class Solution: def isAnagram(self, s: str, t: str) -> bool: @@ -138,12 +153,13 @@ class Solution: return True ``` -Python写法二(没有使用数组作为哈希表,只是介绍defaultdict这样一种解题思路): +(版本三) 使用defaultdict ```python +from collections import defaultdict + class Solution: def isAnagram(self, s: str, t: str) -> bool: - from collections import defaultdict s_dict = defaultdict(int) t_dict = defaultdict(int) @@ -156,17 +172,40 @@ class Solution: return s_dict == t_dict ``` -Python写法三(没有使用数组作为哈希表,只是介绍Counter这种更方便的解题思路): +(版本四) 使用字典 + +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + + hash_table_s = {} + hash_table_t = {} + + for i in range(len(s)): + hash_table_s[s[i]] = hash_table_s.get(s[i], 0) + 1 + hash_table_t[t[i]] = hash_table_t.get(t[i], 0) + 1 + + return hash_table_s == hash_table_t +``` + +(版本五) 使用排序 ```python -class Solution(object): +class Solution: def isAnagram(self, s: str, t: str) -> bool: - from collections import Counter - a_count = Counter(s) - b_count = Counter(t) - return a_count == b_count + return sorted(s) == sorted(t) ``` +(版本六) 使用Counter + +```python +from collections import Counter +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + return Counter(s) == Counter(t) +``` Go: ```go From 3065cf38604dd672ad128a445b98c356604eb24e Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 20:04:47 -0500 Subject: [PATCH 06/35] =?UTF-8?q?Update=200349.=E4=B8=A4=E4=B8=AA=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E7=9A=84=E4=BA=A4=E9=9B=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...04\347\232\204\344\272\244\351\233\206.md" | 32 +++++++++++++------ 1 file changed, 23 insertions(+), 9 deletions(-) diff --git "a/problems/0349.\344\270\244\344\270\252\346\225\260\347\273\204\347\232\204\344\272\244\351\233\206.md" "b/problems/0349.\344\270\244\344\270\252\346\225\260\347\273\204\347\232\204\344\272\244\351\233\206.md" index 0da0e30c37..c2f6ef46ba 100644 --- "a/problems/0349.\344\270\244\344\270\252\346\225\260\347\273\204\347\232\204\344\272\244\351\233\206.md" +++ "b/problems/0349.\344\270\244\344\270\252\346\225\260\347\273\204\347\232\204\344\272\244\351\233\206.md" @@ -160,22 +160,29 @@ class Solution { ``` Python3: +(版本一) 使用字典和集合 ```python class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: - val_dict = {} - ans = [] + # 使用哈希表存储一个数组中的所有元素 + table = {} for num in nums1: - val_dict[num] = 1 - + table[num] = table.get(num, 0) + 1 + + # 使用集合存储结果 + res = set() for num in nums2: - if num in val_dict.keys() and val_dict[num] == 1: - ans.append(num) - val_dict[num] = 0 + if num in table: + res.add(num) + del table[num] - return ans + return list(res) +``` +(版本二) 使用数组 + +```python -class Solution: # 使用数组方法 +class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: count1 = [0]*1001 count2 = [0]*1001 @@ -190,7 +197,14 @@ class Solution: # 使用数组方法 return result ``` +(版本三) 使用集合 +```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + return list(set(nums1) & set(nums2)) + +``` Go: ```go From eeae3282a87c334f726fc3c8cd5dabd5b71c4612 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 20:25:46 -0500 Subject: [PATCH 07/35] =?UTF-8?q?Update=200202.=E5=BF=AB=E4=B9=90=E6=95=B0?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...2.\345\277\253\344\271\220\346\225\260.md" | 96 +++++++++++++++---- 1 file changed, 76 insertions(+), 20 deletions(-) diff --git "a/problems/0202.\345\277\253\344\271\220\346\225\260.md" "b/problems/0202.\345\277\253\344\271\220\346\225\260.md" index 5ac29e8639..7fe8cd8d75 100644 --- "a/problems/0202.\345\277\253\344\271\220\346\225\260.md" +++ "b/problems/0202.\345\277\253\344\271\220\346\225\260.md" @@ -108,23 +108,14 @@ class Solution { ``` Python: +(版本一)使用集合 ```python class Solution: - def isHappy(self, n: int) -> bool: - def calculate_happy(num): - sum_ = 0 - - # 从个位开始依次取,平方求和 - while num: - sum_ += (num % 10) ** 2 - num = num // 10 - return sum_ - - # 记录中间结果 + def isHappy(self, n: int) -> bool: record = set() while True: - n = calculate_happy(n) + n = self.get_sum(n) if n == 1: return True @@ -134,21 +125,86 @@ class Solution: else: record.add(n) -# python的另一种写法 - 通过字符串来计算各位平方和 + def get_sum(self,n: int) -> int: + new_num = 0 + while n: + n, r = divmod(n, 10) + new_num += r ** 2 + return new_num + ``` + (版本二)使用集合 + ```python +class Solution: + def isHappy(self, n: int) -> bool: + record = set() + while n not in record: + record.add(n) + new_num = 0 + n_str = str(n) + for i in n_str: + new_num+=int(i)**2 + if new_num==1: return True + else: n = new_num + return False +``` + (版本三)使用数组 + ```python class Solution: def isHappy(self, n: int) -> bool: record = [] while n not in record: record.append(n) - newn = 0 - nn = str(n) - for i in nn: - newn+=int(i)**2 - if newn==1: return True - n = newn + new_num = 0 + n_str = str(n) + for i in n_str: + new_num+=int(i)**2 + if new_num==1: return True + else: n = new_num return False ``` - + (版本四)使用快慢指针 + ```python +class Solution: + def isHappy(self, n: int) -> bool: + slow = n + fast = n + while self.get_sum(fast) != 1 and self.get_sum(self.get_sum(fast)): + slow = self.get_sum(slow) + fast = self.get_sum(self.get_sum(fast)) + if slow == fast: + return False + return True + def get_sum(self,n: int) -> int: + new_num = 0 + while n: + n, r = divmod(n, 10) + new_num += r ** 2 + return new_num +``` + (版本五)使用集合+精简 + ```python +class Solution: + def isHappy(self, n: int) -> bool: + seen = set() + while n != 1: + n = sum(int(i) ** 2 for i in str(n)) + if n in seen: + return False + seen.add(n) + return True +``` + (版本六)使用数组+精简 + ```python +class Solution: + def isHappy(self, n: int) -> bool: + seen = [] + while n != 1: + n = sum(int(i) ** 2 for i in str(n)) + if n in seen: + return False + seen.append(n) + return True +``` Go: ```go func isHappy(n int) bool { From 7118f36b66e1def134fda97e992affbd0c5cd79b Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 20:38:05 -0500 Subject: [PATCH 08/35] =?UTF-8?q?Update=200001.=E4=B8=A4=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...44\346\225\260\344\271\213\345\222\214.md" | 49 ++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git "a/problems/0001.\344\270\244\346\225\260\344\271\213\345\222\214.md" "b/problems/0001.\344\270\244\346\225\260\344\271\213\345\222\214.md" index eea3ba7a44..1af8787bab 100644 --- "a/problems/0001.\344\270\244\346\225\260\344\271\213\345\222\214.md" +++ "b/problems/0001.\344\270\244\346\225\260\344\271\213\345\222\214.md" @@ -151,7 +151,7 @@ public int[] twoSum(int[] nums, int target) { ``` Python: - +(版本一) 使用字典 ```python class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: @@ -163,6 +163,53 @@ class Solution: records[value] = index # 遍历当前元素,并在map中寻找是否有匹配的key return [] ``` +(版本二)使用集合 +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + #创建一个集合来存储我们目前看到的数字 + seen = set() + for i, num in enumerate(nums): + complement = target - num + if complement in seen: + return [nums.index(complement), i] + seen.add(num) +``` +(版本三)使用双指针 +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + # 对输入列表进行排序 + nums_sorted = sorted(nums) + + # 使用双指针 + left = 0 + right = len(nums_sorted) - 1 + while left < right: + current_sum = nums_sorted[left] + nums_sorted[right] + if current_sum == target: + # 如果和等于目标数,则返回两个数的下标 + left_index = nums.index(nums_sorted[left]) + right_index = nums.index(nums_sorted[right]) + if left_index == right_index: + right_index = nums[left_index+1:].index(nums_sorted[right]) + left_index + 1 + return [left_index, right_index] + elif current_sum < target: + # 如果总和小于目标,则将左侧指针向右移动 + left += 1 + else: + # 如果总和大于目标值,则将右指针向左移动 + right -= 1 +``` +(版本四)暴力法 +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + for i in range(len(nums)): + for j in range(i+1, len(nums)): + if nums[i] + nums[j] == target: + return [i,j] +``` Go: From 0905d2c7871daca4adb18566f86216a83e7894bc Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 20:46:57 -0500 Subject: [PATCH 09/35] =?UTF-8?q?Update=200454.=E5=9B=9B=E6=95=B0=E7=9B=B8?= =?UTF-8?q?=E5=8A=A0II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...3\233\346\225\260\347\233\270\345\212\240II.md" | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git "a/problems/0454.\345\233\233\346\225\260\347\233\270\345\212\240II.md" "b/problems/0454.\345\233\233\346\225\260\347\233\270\345\212\240II.md" index 411b60e872..7818c02b5d 100644 --- "a/problems/0454.\345\233\233\346\225\260\347\233\270\345\212\240II.md" +++ "b/problems/0454.\345\233\233\346\225\260\347\233\270\345\212\240II.md" @@ -125,11 +125,11 @@ class Solution { ``` Python: - +(版本一) 使用字典 ```python class Solution(object): def fourSumCount(self, nums1, nums2, nums3, nums4): - # use a dict to store the elements in nums1 and nums2 and their sum + # 使用字典存储nums1和nums2中的元素及其和 hashmap = dict() for n1 in nums1: for n2 in nums2: @@ -138,7 +138,7 @@ class Solution(object): else: hashmap[n1+n2] = 1 - # if the -(a+b) exists in nums3 and nums4, we shall add the count + # 如果 -(n1+n2) 存在于nums3和nums4, 存入结果 count = 0 for n3 in nums3: for n4 in nums4: @@ -149,20 +149,18 @@ class Solution(object): ``` - +(版本二)使用 defaultdict ```python +from collections import defaultdict class Solution: def fourSumCount(self, nums1: list, nums2: list, nums3: list, nums4: list) -> int: - from collections import defaultdict # You may use normal dict instead. rec, cnt = defaultdict(lambda : 0), 0 - # To store the summary of all the possible combinations of nums1 & nums2, together with their frequencies. for i in nums1: for j in nums2: rec[i+j] += 1 - # To add up the frequencies if the corresponding value occurs in the dictionary for i in nums3: for j in nums4: - cnt += rec.get(-(i+j), 0) # No matched key, return 0. + cnt += rec.get(-(i+j), 0) return cnt ``` From 5cff41ab09e2b3866f3245c3d06d61b3b432f485 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 20:53:12 -0500 Subject: [PATCH 10/35] =?UTF-8?q?Update=200454.=E5=9B=9B=E6=95=B0=E7=9B=B8?= =?UTF-8?q?=E5=8A=A0II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...\346\225\260\347\233\270\345\212\240II.md" | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git "a/problems/0454.\345\233\233\346\225\260\347\233\270\345\212\240II.md" "b/problems/0454.\345\233\233\346\225\260\347\233\270\345\212\240II.md" index 7818c02b5d..31f0504f12 100644 --- "a/problems/0454.\345\233\233\346\225\260\347\233\270\345\212\240II.md" +++ "b/problems/0454.\345\233\233\346\225\260\347\233\270\345\212\240II.md" @@ -149,7 +149,29 @@ class Solution(object): ``` -(版本二)使用 defaultdict +(版本二) 使用字典 +```python +class Solution(object): + def fourSumCount(self, nums1, nums2, nums3, nums4): + # 使用字典存储nums1和nums2中的元素及其和 + hashmap = dict() + for n1 in nums1: + for n2 in nums2: + hashmap[n1+n2] = hashmap.get(n1+n2, 0) + 1 + + # 如果 -(n1+n2) 存在于nums3和nums4, 存入结果 + count = 0 + for n3 in nums3: + for n4 in nums4: + key = - n3 - n4 + if key in hashmap: + count += hashmap[key] + return count + + + +``` +(版本三)使用 defaultdict ```python from collections import defaultdict class Solution: From 38bc7021c6f15136e32785398ad17fdab9098d2b Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 21:05:34 -0500 Subject: [PATCH 11/35] =?UTF-8?q?Update=200383.=E8=B5=8E=E9=87=91=E4=BF=A1?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...3.\350\265\216\351\207\221\344\277\241.md" | 86 +++++++------------ 1 file changed, 31 insertions(+), 55 deletions(-) diff --git "a/problems/0383.\350\265\216\351\207\221\344\277\241.md" "b/problems/0383.\350\265\216\351\207\221\344\277\241.md" index d9a184b643..c2d80d8d89 100644 --- "a/problems/0383.\350\265\216\351\207\221\344\277\241.md" +++ "b/problems/0383.\350\265\216\351\207\221\344\277\241.md" @@ -142,34 +142,27 @@ class Solution { ``` -Python写法一(使用数组作为哈希表): - +(版本一)使用数组 ```python class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: - - arr = [0] * 26 - - for x in magazine: # 记录 magazine里各个字符出现次数 - arr[ord(x) - ord('a')] += 1 - - for x in ransomNote: # 在arr里对应的字符个数做--操作 - if arr[ord(x) - ord('a')] == 0: # 如果没有出现过直接返回 - return False - else: - arr[ord(x) - ord('a')] -= 1 - - return True + ransom_count = [0] * 26 + magazine_count = [0] * 26 + for c in ransomNote: + ransom_count[ord(c) - ord('a')] += 1 + for c in magazine: + magazine_count[ord(c) - ord('a')] += 1 + return all(ransom_count[i] <= magazine_count[i] for i in range(26)) ``` -Python写法二(使用defaultdict): +(版本二)使用defaultdict ```python +from collections import defaultdict + class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: - from collections import defaultdict - hashmap = defaultdict(int) for x in magazine: @@ -177,59 +170,42 @@ class Solution: for x in ransomNote: value = hashmap.get(x) - if value is None or value == 0: + if not value or not value: return False else: hashmap[x] -= 1 return True ``` - -Python写法三: +(版本三)使用字典 ```python -class Solution(object): - def canConstruct(self, ransomNote, magazine): - """ - :type ransomNote: str - :type magazine: str - :rtype: bool - """ - - # use a dict to store the number of letter occurance in ransomNote - hashmap = dict() - for s in ransomNote: - if s in hashmap: - hashmap[s] += 1 - else: - hashmap[s] = 1 - - # check if the letter we need can be found in magazine - for l in magazine: - if l in hashmap: - hashmap[l] -= 1 - - for key in hashmap: - if hashmap[key] > 0: +class Solution: + def canConstruct(self, ransomNote: str, magazine: str) -> bool: + counts = {} + for c in magazine: + counts[c] = counts.get(c, 0) + 1 + for c in ransomNote: + if c not in counts or counts[c] == 0: return False - + counts[c] -= 1 return True ``` +(版本四)使用Counter -Python写法四: +```python +from collections import Counter + +class Solution: + def canConstruct(self, ransomNote: str, magazine: str) -> bool: + return not Counter(ransomNote) - Counter(magazine) +``` +(版本五)使用count ```python class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: - c1 = collections.Counter(ransomNote) - c2 = collections.Counter(magazine) - x = c1 - c2 - #x只保留值大于0的符号,当c1里面的符号个数小于c2时,不会被保留 - #所以x只保留下了,magazine不能表达的 - if(len(x)==0): - return True - else: - return False + return all(ransomNote.count(c) <= magazine.count(c) for c in set(ransomNote)) ``` Go: From 1bc667eccdb247b9795e28a8793ec51fe9ed4883 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 21:06:23 -0500 Subject: [PATCH 12/35] =?UTF-8?q?Update=200383.=E8=B5=8E=E9=87=91=E4=BF=A1?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- "problems/0383.\350\265\216\351\207\221\344\277\241.md" | 1 + 1 file changed, 1 insertion(+) diff --git "a/problems/0383.\350\265\216\351\207\221\344\277\241.md" "b/problems/0383.\350\265\216\351\207\221\344\277\241.md" index c2d80d8d89..7572943786 100644 --- "a/problems/0383.\350\265\216\351\207\221\344\277\241.md" +++ "b/problems/0383.\350\265\216\351\207\221\344\277\241.md" @@ -206,6 +206,7 @@ class Solution: class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: return all(ransomNote.count(c) <= magazine.count(c) for c in set(ransomNote)) + ``` Go: From 2ddbe7f3404ca4c7e70cf3264b6ba4e02327ca78 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 21:30:24 -0500 Subject: [PATCH 13/35] =?UTF-8?q?Update=200015.=E4=B8=89=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...11\346\225\260\344\271\213\345\222\214.md" | 95 +++++++++++-------- 1 file changed, 53 insertions(+), 42 deletions(-) diff --git "a/problems/0015.\344\270\211\346\225\260\344\271\213\345\222\214.md" "b/problems/0015.\344\270\211\346\225\260\344\271\213\345\222\214.md" index 26c9eaa284..9cca779b21 100644 --- "a/problems/0015.\344\270\211\346\225\260\344\271\213\345\222\214.md" +++ "b/problems/0015.\344\270\211\346\225\260\344\271\213\345\222\214.md" @@ -298,61 +298,72 @@ class Solution { ``` Python: +(版本一) 双指针 ```Python class Solution: - def threeSum(self, nums): - ans = [] - n = len(nums) + def threeSum(self, nums: List[int]) -> List[List[int]]: + result = [] nums.sort() - # 找出a + b + c = 0 - # a = nums[i], b = nums[left], c = nums[right] - for i in range(n): - left = i + 1 - right = n - 1 - # 排序之后如果第一个元素已经大于零,那么无论如何组合都不可能凑成三元组,直接返回结果就可以了 - if nums[i] > 0: - break - if i >= 1 and nums[i] == nums[i - 1]: # 去重a + + for i in range(len(nums)): + # 如果第一个元素已经大于0,不需要进一步检查 + if nums[i] > 0: + return result + + # 跳过相同的元素以避免重复 + if i > 0 and nums[i] == nums[i - 1]: continue - while left < right: - total = nums[i] + nums[left] + nums[right] - if total > 0: - right -= 1 - elif total < 0: + + left = i + 1 + right = len(nums) - 1 + + while right > left: + sum_ = nums[i] + nums[left] + nums[right] + + if sum_ < 0: left += 1 + elif sum_ > 0: + right -= 1 else: - ans.append([nums[i], nums[left], nums[right]]) - # 去重逻辑应该放在找到一个三元组之后,对b 和 c去重 - while left != right and nums[left] == nums[left + 1]: left += 1 - while left != right and nums[right] == nums[right - 1]: right -= 1 - left += 1 + result.append([nums[i], nums[left], nums[right]]) + + # 跳过相同的元素以避免重复 + while right > left and nums[right] == nums[right - 1]: + right -= 1 + while right > left and nums[left] == nums[left + 1]: + left += 1 + right -= 1 - return ans + left += 1 + + return result ``` -Python (v3): +(版本二) 使用字典 ```python class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: - if len(nums) < 3: return [] - nums, res = sorted(nums), [] - for i in range(len(nums) - 2): - cur, l, r = nums[i], i + 1, len(nums) - 1 - if res != [] and res[-1][0] == cur: continue # Drop duplicates for the first time. - - while l < r: - if cur + nums[l] + nums[r] == 0: - res.append([cur, nums[l], nums[r]]) - # Drop duplicates for the second time in interation of l & r. Only used when target situation occurs, because that is the reason for dropping duplicates. - while l < r - 1 and nums[l] == nums[l + 1]: - l += 1 - while r > l + 1 and nums[r] == nums[r - 1]: - r -= 1 - if cur + nums[l] + nums[r] > 0: - r -= 1 + result = [] + nums.sort() + # 找出a + b + c = 0 + # a = nums[i], b = nums[j], c = -(a + b) + for i in range(len(nums)): + # 排序之后如果第一个元素已经大于零,那么不可能凑成三元组 + if nums[i] > 0: + break + if i > 0 and nums[i] == nums[i - 1]: #三元组元素a去重 + continue + d = {} + for j in range(i + 1, len(nums)): + if j > i + 2 and nums[j] == nums[j-1] == nums[j-2]: # 三元组元素b去重 + continue + c = 0 - (nums[i] + nums[j]) + if c in d: + result.append([nums[i], nums[j], c]) + d.pop(c) # 三元组元素c去重 else: - l += 1 - return res + d[nums[j]] = j + return result ``` Go: From a5bb942c95f405181ba311e14e1ad601bcfbf435 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 21:35:49 -0500 Subject: [PATCH 14/35] =?UTF-8?q?Update=200018.=E5=9B=9B=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...33\346\225\260\344\271\213\345\222\214.md" | 53 ++++++++++--------- 1 file changed, 29 insertions(+), 24 deletions(-) diff --git "a/problems/0018.\345\233\233\346\225\260\344\271\213\345\222\214.md" "b/problems/0018.\345\233\233\346\225\260\344\271\213\345\222\214.md" index 5f4c2ec920..8606b2ebd0 100644 --- "a/problems/0018.\345\233\233\346\225\260\344\271\213\345\222\214.md" +++ "b/problems/0018.\345\233\233\346\225\260\344\271\213\345\222\214.md" @@ -207,35 +207,40 @@ class Solution { ``` Python: +(版本一) 双指针 ```python -# 双指针法 -class Solution: - def fourSum(self, nums: List[int], target: int) -> List[List[int]]: - + def fourSum(self, nums: List[int], target: int) -> List[List[int]]: + result = [] nums.sort() - n = len(nums) - res = [] - for i in range(n): - if i > 0 and nums[i] == nums[i - 1]: continue # 对nums[i]去重 - for k in range(i+1, n): - if k > i + 1 and nums[k] == nums[k-1]: continue # 对nums[k]去重 - p = k + 1 - q = n - 1 - - while p < q: - if nums[i] + nums[k] + nums[p] + nums[q] > target: q -= 1 - elif nums[i] + nums[k] + nums[p] + nums[q] < target: p += 1 + for k in range(len(nums)): + if nums[k] > target and nums[k] >= 0: + break + if k > 0 and nums[k] == nums[k-1]: + continue + for i in range(k+1, len(nums)): + if nums[k] + nums[i] > target and nums[k] + nums[i] >= 0: + break + if i > k+1 and nums[i] == nums[i-1]: + continue + left, right = i+1, len(nums)-1 + while right > left: + if nums[k] + nums[i] + nums[left] + nums[right] > target: + right -= 1 + elif nums[k] + nums[i] + nums[left] + nums[right] < target: + left += 1 else: - res.append([nums[i], nums[k], nums[p], nums[q]]) - # 对nums[p]和nums[q]去重 - while p < q and nums[p] == nums[p + 1]: p += 1 - while p < q and nums[q] == nums[q - 1]: q -= 1 - p += 1 - q -= 1 - return res + result.append([nums[k], nums[i], nums[left], nums[right]]) + while right > left and nums[right] == nums[right-1]: + right -= 1 + while right > left and nums[left] == nums[left+1]: + left += 1 + right -= 1 + left += 1 + return result ``` +(版本二) 使用字典 + ```python -# 哈希表法 class Solution(object): def fourSum(self, nums, target): """ From dde92b1da3808200925d82f8f523da7b5cd93ca2 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 21:36:38 -0500 Subject: [PATCH 15/35] =?UTF-8?q?Update=200018.=E5=9B=9B=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...33\346\225\260\344\271\213\345\222\214.md" | 40 ++++++++++--------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git "a/problems/0018.\345\233\233\346\225\260\344\271\213\345\222\214.md" "b/problems/0018.\345\233\233\346\225\260\344\271\213\345\222\214.md" index 8606b2ebd0..4fee8358a6 100644 --- "a/problems/0018.\345\233\233\346\225\260\344\271\213\345\222\214.md" +++ "b/problems/0018.\345\233\233\346\225\260\344\271\213\345\222\214.md" @@ -209,34 +209,38 @@ class Solution { Python: (版本一) 双指针 ```python - def fourSum(self, nums: List[int], target: int) -> List[List[int]]: - result = [] +class Solution: + def fourSum(self, nums: List[int], target: int) -> List[List[int]]: nums.sort() - for k in range(len(nums)): - if nums[k] > target and nums[k] >= 0: + n = len(nums) + result = [] + for i in range(n): + if nums[i] > target and nums[i] > 0 and target > 0:# 剪枝(可省) break - if k > 0 and nums[k] == nums[k-1]: + if i > 0 and nums[i] == nums[i-1]:# 去重 continue - for i in range(k+1, len(nums)): - if nums[k] + nums[i] > target and nums[k] + nums[i] >= 0: + for j in range(i+1, n): + if nums[i] + nums[j] > target and target > 0: #剪枝(可省) break - if i > k+1 and nums[i] == nums[i-1]: + if j > i+1 and nums[j] == nums[j-1]: # 去重 continue - left, right = i+1, len(nums)-1 - while right > left: - if nums[k] + nums[i] + nums[left] + nums[right] > target: + left, right = j+1, n-1 + while left < right: + s = nums[i] + nums[j] + nums[left] + nums[right] + if s == target: + result.append([nums[i], nums[j], nums[left], nums[right]]) + while left < right and nums[left] == nums[left+1]: + left += 1 + while left < right and nums[right] == nums[right-1]: + right -= 1 + left += 1 right -= 1 - elif nums[k] + nums[i] + nums[left] + nums[right] < target: + elif s < target: left += 1 else: - result.append([nums[k], nums[i], nums[left], nums[right]]) - while right > left and nums[right] == nums[right-1]: - right -= 1 - while right > left and nums[left] == nums[left+1]: - left += 1 right -= 1 - left += 1 return result + ``` (版本二) 使用字典 From c4bc3197502473c5f14be392157bb83ddaa2dbeb Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Fri, 5 May 2023 21:39:52 -0500 Subject: [PATCH 16/35] =?UTF-8?q?Update=200018.=E5=9B=9B=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...33\346\225\260\344\271\213\345\222\214.md" | 33 +++++++------------ 1 file changed, 11 insertions(+), 22 deletions(-) diff --git "a/problems/0018.\345\233\233\346\225\260\344\271\213\345\222\214.md" "b/problems/0018.\345\233\233\346\225\260\344\271\213\345\222\214.md" index 4fee8358a6..a4d41d9bf9 100644 --- "a/problems/0018.\345\233\233\346\225\260\344\271\213\345\222\214.md" +++ "b/problems/0018.\345\233\233\346\225\260\344\271\213\345\222\214.md" @@ -252,36 +252,25 @@ class Solution(object): :type target: int :rtype: List[List[int]] """ - # use a dict to store value:showtimes - hashmap = dict() - for n in nums: - if n in hashmap: - hashmap[n] += 1 - else: - hashmap[n] = 1 + # 创建一个字典来存储输入列表中每个数字的频率 + freq = {} + for num in nums: + freq[num] = freq.get(num, 0) + 1 - # good thing about using python is you can use set to drop duplicates. + # 创建一个集合来存储最终答案,并遍历4个数字的所有唯一组合 ans = set() - # ans = [] # save results by list() for i in range(len(nums)): for j in range(i + 1, len(nums)): for k in range(j + 1, len(nums)): val = target - (nums[i] + nums[j] + nums[k]) - if val in hashmap: - # make sure no duplicates. + if val in freq: + # 确保没有重复 count = (nums[i] == val) + (nums[j] == val) + (nums[k] == val) - if hashmap[val] > count: - ans_tmp = tuple(sorted([nums[i], nums[j], nums[k], val])) - ans.add(ans_tmp) - # Avoiding duplication in list manner but it cause time complexity increases - # if ans_tmp not in ans: - # ans.append(ans_tmp) - else: - continue - return list(ans) - # if used list() to save results, just - # return ans + if freq[val] > count: + ans.add(tuple(sorted([nums[i], nums[j], nums[k], val]))) + return [list(x) for x in ans] + ``` Go: From b617532ce9b7af1cd163a0ccccb1f956f77e8cd2 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 01:55:48 -0500 Subject: [PATCH 17/35] =?UTF-8?q?Update=200513.=E6=89=BE=E6=A0=91=E5=B7=A6?= =?UTF-8?q?=E4=B8=8B=E8=A7=92=E7=9A=84=E5=80=BC.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...13\350\247\222\347\232\204\345\200\274.md" | 104 +++++++++++------- 1 file changed, 66 insertions(+), 38 deletions(-) diff --git "a/problems/0513.\346\211\276\346\240\221\345\267\246\344\270\213\350\247\222\347\232\204\345\200\274.md" "b/problems/0513.\346\211\276\346\240\221\345\267\246\344\270\213\350\247\222\347\232\204\345\200\274.md" index 5ff254845d..26768c74dc 100644 --- "a/problems/0513.\346\211\276\346\240\221\345\267\246\344\270\213\350\247\222\347\232\204\345\200\274.md" +++ "b/problems/0513.\346\211\276\346\240\221\345\267\246\344\270\213\350\247\222\347\232\204\345\200\274.md" @@ -271,52 +271,80 @@ class Solution { ### Python - -递归: +(版本一)递归法 + 回溯 ```python class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: - max_depth = -float("INF") - leftmost_val = 0 - - def __traverse(root, cur_depth): - nonlocal max_depth, leftmost_val - if not root.left and not root.right: - if cur_depth > max_depth: - max_depth = cur_depth - leftmost_val = root.val - if root.left: - cur_depth += 1 - __traverse(root.left, cur_depth) - cur_depth -= 1 - if root.right: - cur_depth += 1 - __traverse(root.right, cur_depth) - cur_depth -= 1 - - __traverse(root, 0) - return leftmost_val + self.max_depth = float('-inf') + self.result = None + self.traversal(root, 0) + return self.result + + def traversal(self, node, depth): + if not node.left and not node.right: + if depth > self.max_depth: + self.max_depth = depth + self.result = node.val + return + + if node.left: + depth += 1 + self.traversal(node.left, depth) + depth -= 1 + if node.right: + depth += 1 + self.traversal(node.right, depth) + depth -= 1 + ``` -迭代 - 层序遍历: +(版本二)递归法+精简 ```python class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: - queue = deque() - if root: - queue.append(root) - result = 0 - while queue: - q_len = len(queue) - for i in range(q_len): - if i == 0: - result = queue[i].val - cur = queue.popleft() - if cur.left: - queue.append(cur.left) - if cur.right: - queue.append(cur.right) - return result + self.max_depth = float('-inf') + self.result = None + self.traversal(root, 0) + return self.result + + def traversal(self, node, depth): + if not node.left and not node.right: + if depth > self.max_depth: + self.max_depth = depth + self.result = node.val + return + + if node.left: + self.traversal(node.left, depth+1) + if node.right: + self.traversal(node.right, depth+1) +``` + +(版本三) 迭代法 +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +from collections import deque +class Solution: + def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: + queue = deque([root]) + while queue: + size = len(queue) + leftmost = queue[0].val + for i in range(size): + node = queue.popleft() + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + if not queue: + return leftmost + + ``` ### Go From bb8b112ae0079dd0d09d6a075e17888616ba3a55 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 16:51:15 -0500 Subject: [PATCH 18/35] =?UTF-8?q?Update=200344.=E5=8F=8D=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...54\345\255\227\347\254\246\344\270\262.md" | 58 ++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git "a/problems/0344.\345\217\215\350\275\254\345\255\227\347\254\246\344\270\262.md" "b/problems/0344.\345\217\215\350\275\254\345\255\227\347\254\246\344\270\262.md" index 775cfc5872..03c82767d7 100644 --- "a/problems/0344.\345\217\215\350\275\254\345\255\227\347\254\246\344\270\262.md" +++ "b/problems/0344.\345\217\215\350\275\254\345\255\227\347\254\246\344\270\262.md" @@ -174,6 +174,7 @@ class Solution { ``` Python: +(版本一) 双指针 ```python class Solution: def reverseString(self, s: List[str]) -> None: @@ -190,7 +191,62 @@ class Solution: right -= 1 ``` - +(版本二) 使用栈 +```python +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + stack = [] + for char in s: + stack.append(char) + for i in range(len(s)): + s[i] = stack.pop() + +``` +(版本三) 使用range +```python +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + n = len(s) + for i in range(n // 2): + s[i], s[n - i - 1] = s[n - i - 1], s[i] + +``` +(版本四) 使用reversed +```python +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + s[:] = reversed(s) + +``` +(版本五) 使用切片 +```python +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + s[:] = s[::-1] + +``` +(版本六) 使用列表推导 +```python +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + s[:] = [s[i] for i in range(len(s) - 1, -1, -1)] + +``` Go: ```Go func reverseString(s []byte) { From a37ae94618edd6104f9d0815bc0d97e185175f1e Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 16:54:34 -0500 Subject: [PATCH 19/35] =?UTF-8?q?Update=200344.=E5=8F=8D=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...17\215\350\275\254\345\255\227\347\254\246\344\270\262.md" | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git "a/problems/0344.\345\217\215\350\275\254\345\255\227\347\254\246\344\270\262.md" "b/problems/0344.\345\217\215\350\275\254\345\255\227\347\254\246\344\270\262.md" index 03c82767d7..1c74f9aa46 100644 --- "a/problems/0344.\345\217\215\350\275\254\345\255\227\347\254\246\344\270\262.md" +++ "b/problems/0344.\345\217\215\350\275\254\345\255\227\347\254\246\344\270\262.md" @@ -183,8 +183,8 @@ class Solution: """ left, right = 0, len(s) - 1 - # 该方法已经不需要判断奇偶数,经测试后时间空间复杂度比用 for i in range(right//2)更低 - # 推荐该写法,更加通俗易懂 + # 该方法已经不需要判断奇偶数,经测试后时间空间复杂度比用 for i in range(len(s)//2)更低 + # 因为while每次循环需要进行条件判断,而range函数不需要,直接生成数字,因此时间复杂度更低。推荐使用range while left < right: s[left], s[right] = s[right], s[left] left += 1 From abcedd41a87e6923cfd39705765cdd5716b31ad0 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 16:59:12 -0500 Subject: [PATCH 20/35] =?UTF-8?q?Update=20=E5=89=91=E6=8C=87Offer05.?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...7Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" | 1 + 1 file changed, 1 insertion(+) diff --git "a/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" "b/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" index 2e1ee1de1b..833d46284b 100644 --- "a/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" +++ "b/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" @@ -266,6 +266,7 @@ func replaceSpace(s string) string { python: +####因为字符串是不可变类型,所以操作字符串需要将其转换为列表,因此空间复杂度不可能不为O(1) ```python class Solution: def replaceSpace(self, s: str) -> str: From 3958cc166a1ab090f0060e45bab41535170cd186 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 16:59:48 -0500 Subject: [PATCH 21/35] =?UTF-8?q?Update=20=E5=89=91=E6=8C=87Offer05.?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...fer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git "a/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" "b/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" index 833d46284b..d930702fc1 100644 --- "a/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" +++ "b/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" @@ -265,8 +265,8 @@ func replaceSpace(s string) string { -python: -####因为字符串是不可变类型,所以操作字符串需要将其转换为列表,因此空间复杂度不可能不为O(1) +#python: +#因为字符串是不可变类型,所以操作字符串需要将其转换为列表,因此空间复杂度不可能不为O(1) ```python class Solution: def replaceSpace(self, s: str) -> str: From 799325bacebd60e3088e5ab4a82ef599ba1d3e47 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 17:00:54 -0500 Subject: [PATCH 22/35] =?UTF-8?q?Update=20=E5=89=91=E6=8C=87Offer05.?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...fer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git "a/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" "b/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" index d930702fc1..a6c32d3054 100644 --- "a/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" +++ "b/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" @@ -265,8 +265,8 @@ func replaceSpace(s string) string { -#python: -#因为字符串是不可变类型,所以操作字符串需要将其转换为列表,因此空间复杂度不可能不为O(1) +# python: +# 因为字符串是不可变类型,所以操作字符串需要将其转换为列表,因此空间复杂度不可能不为O(1) ```python class Solution: def replaceSpace(self, s: str) -> str: From dc7ac6337d5ae0a462cc332a5a1a68de43095212 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 17:01:39 -0500 Subject: [PATCH 23/35] =?UTF-8?q?Update=20=E5=89=91=E6=8C=87Offer05.?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...fer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git "a/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" "b/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" index a6c32d3054..d86cc6dcf9 100644 --- "a/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" +++ "b/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" @@ -265,8 +265,8 @@ func replaceSpace(s string) string { -# python: -# 因为字符串是不可变类型,所以操作字符串需要将其转换为列表,因此空间复杂度不可能不为O(1) +python: +#### 因为字符串是不可变类型,所以操作字符串需要将其转换为列表,因此空间复杂度不可能不为O(1) ```python class Solution: def replaceSpace(self, s: str) -> str: From c09089accda7c3cc46bc283eb63edfc9563894ab Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 17:10:18 -0500 Subject: [PATCH 24/35] =?UTF-8?q?Update=20=E5=89=91=E6=8C=87Offer05.?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...77\346\215\242\347\251\272\346\240\274.md" | 34 +++++++++++++++---- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git "a/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" "b/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" index d86cc6dcf9..dbad781ef3 100644 --- "a/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" +++ "b/problems/\345\211\221\346\214\207Offer05.\346\233\277\346\215\242\347\251\272\346\240\274.md" @@ -266,7 +266,8 @@ func replaceSpace(s string) string { python: -#### 因为字符串是不可变类型,所以操作字符串需要将其转换为列表,因此空间复杂度不可能不为O(1) +#### 因为字符串是不可变类型,所以操作字符串需要将其转换为列表,因此空间复杂度不可能为O(1) +(版本一)转换成列表,并且添加相匹配的空间,然后进行填充 ```python class Solution: def replaceSpace(self, s: str) -> str: @@ -291,14 +292,22 @@ class Solution: return ''.join(res) ``` - +(版本二)添加空列表,添加匹配的结果 +```python +class Solution: + def replaceSpace(self, s: str) -> str: + res = [] + for i in range(len(s)): + if s[i] == ' ': + res.append('%20') + else: + res.append(s[i]) + return ''.join(res) +``` +(版本三)使用切片 ```python class Solution: def replaceSpace(self, s: str) -> str: - # method 1 - Very rude - return "%20".join(s.split(" ")) - - # method 2 - Reverse the s when counting in for loop, then update from the end. n = len(s) for e, i in enumerate(s[::-1]): print(i, e) @@ -307,7 +316,18 @@ class Solution: print("") return s ``` - +(版本四)使用join + split +```python +class Solution: + def replaceSpace(self, s: str) -> str: + return "%20".join(s.split(" ")) +``` +(版本五)使用replace +```python +class Solution: + def replaceSpace(self, s: str) -> str: + return s.replace(' ', '%20') +``` javaScript: ```js From c75140d2572be2030e64a8aa18a7cc336b7a5a74 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 17:26:08 -0500 Subject: [PATCH 25/35] =?UTF-8?q?Update=200151.=E7=BF=BB=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...14\347\232\204\345\215\225\350\257\215.md" | 142 +++--------------- 1 file changed, 24 insertions(+), 118 deletions(-) diff --git "a/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" "b/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" index 8fa7c77c9e..a323226416 100644 --- "a/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" +++ "b/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" @@ -434,134 +434,40 @@ class Solution { ``` python: - +(版本一)先删除空白,然后整个反转,最后单词反转。 +### 因为字符串是不可变类型,所以反转单词的时候,需要将其转换成列表,然后通过join函数再将其转换成列表,所以空间复杂度不是O(1) ```Python class Solution: - #1.去除多余的空格 - def trim_spaces(self, s): - n = len(s) - left = 0 - right = n-1 - - while left <= right and s[left] == ' ': #去除开头的空格 - left += 1 - while left <= right and s[right] == ' ': #去除结尾的空格 - right -= 1 - tmp = [] - while left <= right: #去除单词中间多余的空格 - if s[left] != ' ': - tmp.append(s[left]) - elif tmp[-1] != ' ': #当前位置是空格,但是相邻的上一个位置不是空格,则该空格是合理的 - tmp.append(s[left]) - left += 1 - return tmp - - #2.翻转字符数组 - def reverse_string(self, nums, left, right): - while left < right: - nums[left], nums[right] = nums[right], nums[left] - left += 1 - right -= 1 - return None - - #3.翻转每个单词 - def reverse_each_word(self, nums): - start = 0 - end = 0 - n = len(nums) - while start < n: - while end < n and nums[end] != ' ': - end += 1 - self.reverse_string(nums, start, end-1) - start = end + 1 - end += 1 - return None - -#4.翻转字符串里的单词 - def reverseWords(self, s): #测试用例:"the sky is blue" - l = self.trim_spaces(s) #输出:['t', 'h', 'e', ' ', 's', 'k', 'y', ' ', 'i', 's', ' ', 'b', 'l', 'u', 'e' - self.reverse_string(l, 0, len(l)-1) #输出:['e', 'u', 'l', 'b', ' ', 's', 'i', ' ', 'y', 'k', 's', ' ', 'e', 'h', 't'] - self.reverse_each_word(l) #输出:['b', 'l', 'u', 'e', ' ', 'i', 's', ' ', 's', 'k', 'y', ' ', 't', 'h', 'e'] - return ''.join(l) #输出:blue is sky the - + def reverseWords(self, s: str) -> str: + # 删除前后空白 + s = s.strip() + # 反转整个字符串 + s = s[::-1] + # 将字符串拆分为单词,并反转每个单词 + s = ' '.join(word[::-1] for word in s.split()) + return s ``` +(版本二)使用双指针 ```python class Solution: def reverseWords(self, s: str) -> str: - # method 1 - Rude but work & efficient method. - s_list = [i for i in s.split(" ") if len(i) > 0] - return " ".join(s_list[::-1]) - - # method 2 - Carlo's idea - def trim_head_tail_space(ss: str): - p = 0 - while p < len(ss) and ss[p] == " ": - p += 1 - return ss[p:] - - # Trim the head and tail space - s = trim_head_tail_space(s) - s = trim_head_tail_space(s[::-1])[::-1] - - pf, ps, s = 0, 0, s[::-1] # Reverse the string. - while pf < len(s): - if s[pf] == " ": - # Will not excede. Because we have clean the tail space. - if s[pf] == s[pf + 1]: - s = s[:pf] + s[pf + 1:] - continue - else: - s = s[:ps] + s[ps: pf][::-1] + s[pf:] - ps, pf = pf + 1, pf + 2 - else: - pf += 1 - return s[:ps] + s[ps:][::-1] # Must do the last step, because the last word is omit though the pointers are on the correct positions, + # 将字符串拆分为单词,即转换成列表类型 + words = s.split() + + # 反转单词 + left, right = 0, len(words) - 1 + while left < right: + words[left], words[right] = words[right], words[left] + left += 1 + right -= 1 + + # 将列表转换成字符串 + return " ".join(words) ``` -```python -class Solution: # 使用双指针法移除空格 - def reverseWords(self, s: str) -> str: - - def removeextraspace(s): - start = 0; end = len(s)-1 - while s[start]==' ': - start+=1 - while s[end]==' ': - end-=1 - news = list(s[start:end+1]) - slow = fast = 0 - while fast0 and news[fast]==news[fast-1]==' ': - fast+=1 - news[slow]=news[fast] - slow+=1; fast+=1 - #return "".join(news[:slow]) - return news[:slow] - - def reversestr(s): - left,right = 0,len(s)-1 - news = list(s) - while left Date: Sat, 6 May 2023 17:26:56 -0500 Subject: [PATCH 26/35] =?UTF-8?q?Update=200151.=E7=BF=BB=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git "a/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" "b/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" index a323226416..062ccca538 100644 --- "a/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" +++ "b/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" @@ -435,7 +435,7 @@ class Solution { python: (版本一)先删除空白,然后整个反转,最后单词反转。 -### 因为字符串是不可变类型,所以反转单词的时候,需要将其转换成列表,然后通过join函数再将其转换成列表,所以空间复杂度不是O(1) +#### 因为字符串是不可变类型,所以反转单词的时候,需要将其转换成列表,然后通过join函数再将其转换成列表,所以空间复杂度不是O(1) ```Python class Solution: def reverseWords(self, s: str) -> str: From 7cfd38940249adb1f659da29b69edc2ae3083113 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 17:52:08 -0500 Subject: [PATCH 27/35] =?UTF-8?q?Update=20=E5=89=91=E6=8C=87Offer58-II.?= =?UTF-8?q?=E5=B7=A6=E6=97=8B=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...54\345\255\227\347\254\246\344\270\262.md" | 54 ++++++++++--------- 1 file changed, 28 insertions(+), 26 deletions(-) diff --git "a/problems/\345\211\221\346\214\207Offer58-II.\345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262.md" "b/problems/\345\211\221\346\214\207Offer58-II.\345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262.md" index f368514f4b..6cd8845609 100644 --- "a/problems/\345\211\221\346\214\207Offer58-II.\345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262.md" +++ "b/problems/\345\211\221\346\214\207Offer58-II.\345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262.md" @@ -142,15 +142,16 @@ class Solution { ``` python: +(版本一)使用切片 ```python -# 方法一:可以使用切片方法 class Solution: def reverseLeftWords(self, s: str, n: int) -> str: - return s[n:] + s[0:n] + return s[n:] + s[:n] ``` +(版本二)使用reversed + join + ```python -# 方法二:也可以使用上文描述的方法,有些面试中不允许使用切片,那就使用上文作者提到的方法 class Solution: def reverseLeftWords(self, s: str, n: int) -> str: s = list(s) @@ -161,32 +162,29 @@ class Solution: return "".join(s) ``` +(版本三)自定义reversed函数 ```python -# 方法三:如果连reversed也不让使用,那么自己手写一个 class Solution: - def reverseLeftWords(self, s: str, n: int) -> str: - def reverse_sub(lst, left, right): - while left < right: - lst[left], lst[right] = lst[right], lst[left] - left += 1 - right -= 1 + def reverseLeftWords(self, s: str, n: int) -> str: + s_list = list(s) - res = list(s) - end = len(res) - 1 - reverse_sub(res, 0, n - 1) - reverse_sub(res, n, end) - reverse_sub(res, 0, end) - return ''.join(res) + self.reverse(s_list, 0, n - 1) + self.reverse(s_list, n, len(s_list) - 1) + self.reverse(s_list, 0, len(s_list) - 1) -# 同方法二 -# 时间复杂度:O(n) -# 空间复杂度:O(n),python的string为不可变,需要开辟同样大小的list空间来修改 + return ''.join(s_list) + + def reverse(self, s, start, end): + while start < end: + s[start], s[end] = s[end], s[start] + start += 1 + end -= 1 ``` +(版本四)使用 模 +下标 ```python 3 -#方法四:考虑不能用切片的情况下,利用模+下标实现 class Solution: def reverseLeftWords(self, s: str, n: int) -> str: new_s = '' @@ -196,17 +194,21 @@ class Solution: return new_s ``` +(版本五)使用 模 + 切片 ```python 3 -# 方法五:另类的切片方法 class Solution: def reverseLeftWords(self, s: str, n: int) -> str: - n = len(s) - s = s + s - return s[k : n+k] + l = len(s) + # 复制输入字符串与它自己连接 + s = s + s + + # 计算旋转字符串的起始索引 + k = n % (l * 2) + + # 从连接的字符串中提取旋转后的字符串并返回 + return s[k : k + l] -# 时间复杂度:O(n) -# 空间复杂度:O(n) ``` Go: From 3cf55028680832e76c82f9f819443b79339f1d49 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 19:39:34 -0500 Subject: [PATCH 28/35] =?UTF-8?q?Update=200028.=E5=AE=9E=E7=8E=B0strStr.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0028.\345\256\236\347\216\260strStr.md" | 99 +++++++++++-------- 1 file changed, 59 insertions(+), 40 deletions(-) diff --git "a/problems/0028.\345\256\236\347\216\260strStr.md" "b/problems/0028.\345\256\236\347\216\260strStr.md" index 263c168995..5cc0499467 100644 --- "a/problems/0028.\345\256\236\347\216\260strStr.md" +++ "b/problems/0028.\345\256\236\347\216\260strStr.md" @@ -692,23 +692,38 @@ class Solution { ``` Python3: +(版本一)前缀表(不减一) + ```python -//暴力解法: -class Solution(object): - def strStr(self, haystack, needle): - """ - :type haystack: str - :type needle: str - :rtype: int - """ - m, n = len(haystack), len(needle) - for i in range(m): - if haystack[i:i+n] == needle: - return i - return -1 +class Solution: + def strStr(self, haystack: str, needle: str) -> int: + if len(needle) == 0: + return 0 + next = self.getNext(needle) + j = 0 + for i in range(len(haystack)): + while j >= 1 and haystack[i] != needle[j]: + j = next[j-1] + if haystack[i] == needle[j]: + j += 1 + if j == len(needle): + return i - len(needle) + 1 + return -1 + + def getNext(self, needle): + next = [0] * len(needle) + j = 0 + next[0] = j + for i in range(1, len(needle)): + while j >= 1 and needle[i] != needle[j]: + j = next[j-1] + if needle[i] == needle[j]: + j += 1 + next[i] = j + return next ``` +(版本二)前缀表(减一) ```python -// 方法一 class Solution: def strStr(self, haystack: str, needle: str) -> int: a = len(needle) @@ -739,8 +754,11 @@ class Solution: return next ``` + +(版本三)前缀表(减一) + + ```python -// 方法二 class Solution: def strStr(self, haystack: str, needle: str) -> int: a = len(needle) @@ -774,35 +792,36 @@ class Solution: return next ``` +(版本四)暴力法 +```python +class Solution(object): + def strStr(self, haystack, needle): + """ + :type haystack: str + :type needle: str + :rtype: int + """ + m, n = len(haystack), len(needle) + for i in range(m): + if haystack[i:i+n] == needle: + return i + return -1 +``` +(版本五)使用 index ```python -// 前缀表(不减一)Python实现 class Solution: def strStr(self, haystack: str, needle: str) -> int: - if len(needle) == 0: - return 0 - next = self.getNext(needle) - j = 0 - for i in range(len(haystack)): - while j >= 1 and haystack[i] != needle[j]: - j = next[j-1] - if haystack[i] == needle[j]: - j += 1 - if j == len(needle): - return i - len(needle) + 1 - return -1 - - def getNext(self, needle): - next = [0] * len(needle) - j = 0 - next[0] = j - for i in range(1, len(needle)): - while j >= 1 and needle[i] != needle[j]: - j = next[j-1] - if needle[i] == needle[j]: - j += 1 - next[i] = j - return next + try: + return haystack.index(needle) + except ValueError: + return -1 ``` +(版本六)使用 find +```python +class Solution: + def strStr(self, haystack: str, needle: str) -> int: + return haystack.find(needle) + Go: From 1fbd900c6a942b86d9c1d2f394ed89023e22a50d Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 19:47:55 -0500 Subject: [PATCH 29/35] =?UTF-8?q?Update=200028.=E5=AE=9E=E7=8E=B0strStr.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0028.\345\256\236\347\216\260strStr.md" | 131 ++++++------------ 1 file changed, 45 insertions(+), 86 deletions(-) diff --git "a/problems/0028.\345\256\236\347\216\260strStr.md" "b/problems/0028.\345\256\236\347\216\260strStr.md" index 5cc0499467..ff13db3910 100644 --- "a/problems/0028.\345\256\236\347\216\260strStr.md" +++ "b/problems/0028.\345\256\236\347\216\260strStr.md" @@ -692,107 +692,66 @@ class Solution { ``` Python3: -(版本一)前缀表(不减一) - +(版本一)前缀表(减一) ```python class Solution: - def strStr(self, haystack: str, needle: str) -> int: - if len(needle) == 0: - return 0 - next = self.getNext(needle) - j = 0 - for i in range(len(haystack)): - while j >= 1 and haystack[i] != needle[j]: - j = next[j-1] - if haystack[i] == needle[j]: - j += 1 - if j == len(needle): - return i - len(needle) + 1 - return -1 - - def getNext(self, needle): - next = [0] * len(needle) - j = 0 + def getNext(self, next, s): + j = -1 next[0] = j - for i in range(1, len(needle)): - while j >= 1 and needle[i] != needle[j]: - j = next[j-1] - if needle[i] == needle[j]: + for i in range(1, len(s)): + while j >= 0 and s[i] != s[j+1]: + j = next[j] + if s[i] == s[j+1]: j += 1 next[i] = j - return next -``` -(版本二)前缀表(减一) -```python -class Solution: + def strStr(self, haystack: str, needle: str) -> int: - a = len(needle) - b = len(haystack) - if a == 0: + if not needle: return 0 - next = self.getnext(a,needle) - p=-1 - for j in range(b): - while p >= 0 and needle[p+1] != haystack[j]: - p = next[p] - if needle[p+1] == haystack[j]: - p += 1 - if p == a-1: - return j-a+1 + next = [0] * len(needle) + self.getNext(next, needle) + j = -1 + for i in range(len(haystack)): + while j >= 0 and haystack[i] != needle[j+1]: + j = next[j] + if haystack[i] == needle[j+1]: + j += 1 + if j == len(needle) - 1: + return i - len(needle) + 1 return -1 - - def getnext(self,a,needle): - next = ['' for i in range(a)] - k = -1 - next[0] = k - for i in range(1, len(needle)): - while (k > -1 and needle[k+1] != needle[i]): - k = next[k] - if needle[k+1] == needle[i]: - k += 1 - next[i] = k - return next ``` - - -(版本三)前缀表(减一) - +(版本二)前缀表(不减一) ```python class Solution: + def getNext(self, next: List[int], s: str) -> None: + j = 0 + next[0] = 0 + for i in range(1, len(s)): + while j > 0 and s[i] != s[j]: + j = next[j - 1] + if s[i] == s[j]: + j += 1 + next[i] = j + def strStr(self, haystack: str, needle: str) -> int: - a = len(needle) - b = len(haystack) - if a == 0: + if len(needle) == 0: return 0 - i = j = 0 - next = self.getnext(a, needle) - while(i < b and j < a): - if j == -1 or needle[j] == haystack[i]: - i += 1 - j += 1 - else: - j = next[j] - if j == a: - return i-j - else: - return -1 - - def getnext(self, a, needle): - next = ['' for i in range(a)] - j, k = 0, -1 - next[0] = k - while(j < a-1): - if k == -1 or needle[k] == needle[j]: - k += 1 + next = [0] * len(needle) + self.getNext(next, needle) + j = 0 + for i in range(len(haystack)): + while j > 0 and haystack[i] != needle[j]: + j = next[j - 1] + if haystack[i] == needle[j]: j += 1 - next[j] = k - else: - k = next[k] - return next + if j == len(needle): + return i - len(needle) + 1 + return -1 ``` -(版本四)暴力法 + +(版本三)暴力法 ```python class Solution(object): def strStr(self, haystack, needle): @@ -807,7 +766,7 @@ class Solution(object): return i return -1 ``` -(版本五)使用 index +(版本四)使用 index ```python class Solution: def strStr(self, haystack: str, needle: str) -> int: @@ -816,7 +775,7 @@ class Solution: except ValueError: return -1 ``` -(版本六)使用 find +(版本五)使用 find ```python class Solution: def strStr(self, haystack: str, needle: str) -> int: From 995028d7c45099f71d9ef398ad92a8b655e0c4f9 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 19:48:45 -0500 Subject: [PATCH 30/35] =?UTF-8?q?Update=200028.=E5=AE=9E=E7=8E=B0strStr.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- "problems/0028.\345\256\236\347\216\260strStr.md" | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git "a/problems/0028.\345\256\236\347\216\260strStr.md" "b/problems/0028.\345\256\236\347\216\260strStr.md" index ff13db3910..b18131f391 100644 --- "a/problems/0028.\345\256\236\347\216\260strStr.md" +++ "b/problems/0028.\345\256\236\347\216\260strStr.md" @@ -780,7 +780,7 @@ class Solution: class Solution: def strStr(self, haystack: str, needle: str) -> int: return haystack.find(needle) - +``` Go: From e8b4db9d7a5cf58e56e58254195cc2a98d926479 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 19:49:19 -0500 Subject: [PATCH 31/35] =?UTF-8?q?Update=200028.=E5=AE=9E=E7=8E=B0strStr.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- "problems/0028.\345\256\236\347\216\260strStr.md" | 1 + 1 file changed, 1 insertion(+) diff --git "a/problems/0028.\345\256\236\347\216\260strStr.md" "b/problems/0028.\345\256\236\347\216\260strStr.md" index b18131f391..86308b4799 100644 --- "a/problems/0028.\345\256\236\347\216\260strStr.md" +++ "b/problems/0028.\345\256\236\347\216\260strStr.md" @@ -780,6 +780,7 @@ class Solution: class Solution: def strStr(self, haystack: str, needle: str) -> int: return haystack.find(needle) + ``` Go: From 5000a978fd41dd32a639935459365fd58e691c37 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 20:05:02 -0500 Subject: [PATCH 32/35] =?UTF-8?q?Update=200459.=E9=87=8D=E5=A4=8D=E7=9A=84?= =?UTF-8?q?=E5=AD=90=E5=AD=97=E7=AC=A6=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...20\345\255\227\347\254\246\344\270\262.md" | 39 +++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git "a/problems/0459.\351\207\215\345\244\215\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262.md" "b/problems/0459.\351\207\215\345\244\215\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262.md" index 98c02a2544..5d56ad18fb 100644 --- "a/problems/0459.\351\207\215\345\244\215\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262.md" +++ "b/problems/0459.\351\207\215\345\244\215\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262.md" @@ -264,8 +264,7 @@ class Solution { Python: -这里使用了前缀表统一减一的实现方式 - +(版本一) 前缀表 减一 ```python class Solution: def repeatedSubstringPattern(self, s: str) -> bool: @@ -289,7 +288,7 @@ class Solution: return nxt ``` -前缀表(不减一)的代码实现 +(版本二) 前缀表 不减一 ```python class Solution: @@ -314,6 +313,40 @@ class Solution: return nxt ``` + +(版本三) 使用 find + +```python +class Solution: + def repeatedSubstringPattern(self, s: str) -> bool: + n = len(s) + if n <= 1: + return False + ss = s[1:] + s[:-1] + print(ss.find(s)) + return ss.find(s) != -1 +``` + +(版本四) 暴力法 + +```python +class Solution: + def repeatedSubstringPattern(self, s: str) -> bool: + n = len(s) + if n <= 1: + return False + + substr = "" + for i in range(1, n//2 + 1): + if n % i == 0: + substr = s[:i] + if substr * (n//i) == s: + return True + + return False +``` + + Go: 这里使用了前缀表统一减一的实现方式 From f97ff3a1beeb938107bd76dfa38dac3c93430095 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98Carl?= Date: Sun, 7 May 2023 09:28:28 +0800 Subject: [PATCH 33/35] =?UTF-8?q?Update=200151.=E7=BF=BB=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git "a/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" "b/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" index 062ccca538..4474f1c613 100644 --- "a/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" +++ "b/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" @@ -435,7 +435,7 @@ class Solution { python: (版本一)先删除空白,然后整个反转,最后单词反转。 -#### 因为字符串是不可变类型,所以反转单词的时候,需要将其转换成列表,然后通过join函数再将其转换成列表,所以空间复杂度不是O(1) +**因为字符串是不可变类型,所以反转单词的时候,需要将其转换成列表,然后通过join函数再将其转换成列表,所以空间复杂度不是O(1)** ```Python class Solution: def reverseWords(self, s: str) -> str: From 3f45b56cef522ca54b648ded97a8d3b0c6a0f919 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98Carl?= Date: Sun, 7 May 2023 09:47:01 +0800 Subject: [PATCH 34/35] =?UTF-8?q?Update=200242.=E6=9C=89=E6=95=88=E7=9A=84?= =?UTF-8?q?=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...15\345\274\202\344\275\215\350\257\215.md" | 68 +------------------ 1 file changed, 1 insertion(+), 67 deletions(-) diff --git "a/problems/0242.\346\234\211\346\225\210\347\232\204\345\255\227\346\257\215\345\274\202\344\275\215\350\257\215.md" "b/problems/0242.\346\234\211\346\225\210\347\232\204\345\255\227\346\257\215\345\274\202\344\275\215\350\257\215.md" index 0e5683c794..3f4b00dc30 100644 --- "a/problems/0242.\346\234\211\346\225\210\347\232\204\345\255\227\346\257\215\345\274\202\344\275\215\350\257\215.md" +++ "b/problems/0242.\346\234\211\346\225\210\347\232\204\345\255\227\346\257\215\345\274\202\344\275\215\350\257\215.md" @@ -122,21 +122,7 @@ class Solution { ``` Python: -(版本一) 使用数组 -```python -class Solution: - def isAnagram(self, s: str, t: str) -> bool: - record = [0] * 26 - for i in range(len(s)): - record[ord(s[i]) - ord("a")] += 1 - for i in range(len(t)): - record[ord(t[i]) - ord("a")] -= 1 - for i in range(26): - if record[i] != 0: - return False - return True -``` -(版本二) 使用数组 + ```python class Solution: def isAnagram(self, s: str, t: str) -> bool: @@ -153,59 +139,7 @@ class Solution: return True ``` -(版本三) 使用defaultdict - -```python -from collections import defaultdict - -class Solution: - def isAnagram(self, s: str, t: str) -> bool: - - s_dict = defaultdict(int) - t_dict = defaultdict(int) - - for x in s: - s_dict[x] += 1 - - for x in t: - t_dict[x] += 1 - - return s_dict == t_dict -``` -(版本四) 使用字典 - -```python -class Solution: - def isAnagram(self, s: str, t: str) -> bool: - if len(s) != len(t): - return False - - hash_table_s = {} - hash_table_t = {} - - for i in range(len(s)): - hash_table_s[s[i]] = hash_table_s.get(s[i], 0) + 1 - hash_table_t[t[i]] = hash_table_t.get(t[i], 0) + 1 - - return hash_table_s == hash_table_t -``` - -(版本五) 使用排序 -```python -class Solution: - def isAnagram(self, s: str, t: str) -> bool: - return sorted(s) == sorted(t) -``` -(版本六) 使用Counter - -```python -from collections import Counter - -class Solution: - def isAnagram(self, s: str, t: str) -> bool: - return Counter(s) == Counter(t) -``` Go: ```go From 6e88b2034d70d261a9cd0388cdcf906e50677195 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98Carl?= Date: Sun, 7 May 2023 09:54:15 +0800 Subject: [PATCH 35/35] =?UTF-8?q?Update=200242.=E6=9C=89=E6=95=88=E7=9A=84?= =?UTF-8?q?=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...15\345\274\202\344\275\215\350\257\215.md" | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git "a/problems/0242.\346\234\211\346\225\210\347\232\204\345\255\227\346\257\215\345\274\202\344\275\215\350\257\215.md" "b/problems/0242.\346\234\211\346\225\210\347\232\204\345\255\227\346\257\215\345\274\202\344\275\215\350\257\215.md" index 3f4b00dc30..09674ecdaa 100644 --- "a/problems/0242.\346\234\211\346\225\210\347\232\204\345\255\227\346\257\215\345\274\202\344\275\215\350\257\215.md" +++ "b/problems/0242.\346\234\211\346\225\210\347\232\204\345\255\227\346\257\215\345\274\202\344\275\215\350\257\215.md" @@ -138,7 +138,31 @@ class Solution: return False return True ``` +Python写法二(没有使用数组作为哈希表,只是介绍defaultdict这样一种解题思路): +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + from collections import defaultdict + + s_dict = defaultdict(int) + t_dict = defaultdict(int) + for x in s: + s_dict[x] += 1 + + for x in t: + t_dict[x] += 1 + return s_dict == t_dict +``` +Python写法三(没有使用数组作为哈希表,只是介绍Counter这种更方便的解题思路): + +```python +class Solution(object): + def isAnagram(self, s: str, t: str) -> bool: + from collections import Counter + a_count = Counter(s) + b_count = Counter(t) + return a_count == b_count Go: