From 658449f92a37f65c83440ba207b16899cb84d1bc Mon Sep 17 00:00:00 2001 From: yanglbme Date: Fri, 24 May 2024 15:59:34 +0800 Subject: [PATCH 1/3] feat: update solutions to lcof problems --- .../README.md" | 15 +- .../Solution.go" | 4 +- .../Solution.java" | 9 +- .../README.md" | 27 +-- .../Solution2.rs" | 10 - .../README.md" | 45 ---- .../Solution2.go" | 30 --- .../README.md" | 32 --- .../Solution2.py" | 17 -- .../README.md" | 36 --- .../Solution2.py" | 21 -- .../README.md" | 2 +- .../README.md" | 2 +- .../README.md" | 205 +----------------- .../README.md | 2 +- .../README_EN.md | 10 +- .../Solution.ts | 2 +- 17 files changed, 37 insertions(+), 432 deletions(-) delete mode 100644 "lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/Solution2.rs" delete mode 100644 "lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution2.go" delete mode 100644 "lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/Solution2.py" delete mode 100644 "lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/Solution2.py" diff --git "a/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/README.md" index 23ab5c1b6bdbb..57807e611750e 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/README.md" @@ -52,7 +52,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9 由于数组 `nums` 已排好序,我们可以使用二分查找的方法找到数组中第一个大于等于 `target` 的元素的下标 $l$,以及第一个大于 `target` 的元素的下标 $r$,那么 `target` 的个数就是 $r - l$。 -时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。其中 $n$ 为数组的长度。 +时间复杂度 $O(\log n)$,其中 $n$ 为数组的长度。空间复杂度 $O(1)$。 @@ -70,13 +70,16 @@ class Solution: ```java class Solution { + private int[] nums; + public int search(int[] nums, int target) { - int l = lowerBound(nums, target); - int r = lowerBound(nums, target + 1); + this.nums = nums; + int l = search(target); + int r = search(target + 1); return r - l; } - private int lowerBound(int[] nums, int x) { + private int search(int x) { int l = 0, r = nums.length; while (l < r) { int mid = (l + r) >>> 1; @@ -108,8 +111,8 @@ public: ```go func search(nums []int, target int) int { - l := sort.Search(len(nums), func(i int) bool { return nums[i] >= target }) - r := sort.Search(len(nums), func(i int) bool { return nums[i] > target }) + l := sort.SearchInts(nums, target) + r := sort.SearchInts(nums, target+1) return r - l } ``` diff --git "a/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/Solution.go" index 72bf19215e3ff..ebaf08a7f39ce 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/Solution.go" @@ -1,5 +1,5 @@ func search(nums []int, target int) int { - l := sort.Search(len(nums), func(i int) bool { return nums[i] >= target }) - r := sort.Search(len(nums), func(i int) bool { return nums[i] > target }) + l := sort.SearchInts(nums, target) + r := sort.SearchInts(nums, target+1) return r - l } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/Solution.java" index 4b83c3fd46b7d..de37b528777c2 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/Solution.java" @@ -1,11 +1,14 @@ class Solution { + private int[] nums; + public int search(int[] nums, int target) { - int l = lowerBound(nums, target); - int r = lowerBound(nums, target + 1); + this.nums = nums; + int l = search(target); + int r = search(target + 1); return r - l; } - private int lowerBound(int[] nums, int x) { + private int search(int x) { int l = 0, r = nums.length; while (l < r) { int mid = (l + r) >>> 1; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/README.md" index 37d5ef58fb1ee..501b414e36aca 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/README.md" @@ -46,7 +46,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9 最后返回左边界 $l$ 即可。 -时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。其中 $n$ 是数组的长度。 +时间复杂度 $O(\log n)$,其中 $n$ 是数组的长度。空间复杂度 $O(1)$。 @@ -185,29 +185,4 @@ public class Solution { - - -### 方法二 - - - -#### Rust - -```rust -impl Solution { - pub fn missing_number(nums: Vec) -> i32 { - let n = nums.len() as i32; - let mut sum = ((1 + n) * n) / 2; - for num in nums.iter() { - sum -= num; - } - sum - } -} -``` - - - - - diff --git "a/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/Solution2.rs" "b/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/Solution2.rs" deleted file mode 100644 index d798edb978118..0000000000000 --- "a/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/Solution2.rs" +++ /dev/null @@ -1,10 +0,0 @@ -impl Solution { - pub fn missing_number(nums: Vec) -> i32 { - let n = nums.len() as i32; - let mut sum = ((1 + n) * n) / 2; - for num in nums.iter() { - sum -= num; - } - sum - } -} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/README.md" index c0cbd61793288..7320ed92a469c 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/README.md" @@ -335,49 +335,4 @@ public class Solution { - - -### 方法二 - - - -#### Go - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func kthLargest(root *TreeNode, k int) int { - ch := make(chan int) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - go inorder(ctx, root, ch) - for ; k > 1; k-- { - <-ch - } - return <-ch -} - -func inorder(ctx context.Context, cur *TreeNode, ch chan<- int) { - if cur != nil { - inorder(ctx, cur.Right, ch) - select { - case ch <- cur.Val: - case <-ctx.Done(): - return - } - inorder(ctx, cur.Left, ch) - } -} -``` - - - - - diff --git "a/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution2.go" deleted file mode 100644 index acc10096996db..0000000000000 --- "a/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/Solution2.go" +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func kthLargest(root *TreeNode, k int) int { - ch := make(chan int) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - go inorder(ctx, root, ch) - for ; k > 1; k-- { - <-ch - } - return <-ch -} - -func inorder(ctx context.Context, cur *TreeNode, ch chan<- int) { - if cur != nil { - inorder(ctx, cur.Right, ch) - select { - case ch <- cur.Val: - case <-ctx.Done(): - return - } - inorder(ctx, cur.Left, ch) - } -} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/README.md" index 280c8f2da197d..7f9176a295456 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/README.md" @@ -222,36 +222,4 @@ public class Solution { - - -### 方法二 - - - -#### Python3 - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - - -class Solution: - def maxDepth(self, root: TreeNode) -> int: - def dfs(root): - if root is None: - return 0 - l, r = dfs(root.left), dfs(root.right) - return 1 + max(l, r) - - return dfs(root) -``` - - - - - diff --git "a/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/Solution2.py" deleted file mode 100644 index ca29da983b6cc..0000000000000 --- "a/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/Solution2.py" +++ /dev/null @@ -1,17 +0,0 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - - -class Solution: - def maxDepth(self, root: TreeNode) -> int: - def dfs(root): - if root is None: - return 0 - l, r = dfs(root.left), dfs(root.right) - return 1 + max(l, r) - - return dfs(root) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/README.md" index 656700fec7dba..c8be7f0d0d322 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/README.md" @@ -313,40 +313,4 @@ public class Solution { - - -### 方法二 - - - -#### Python3 - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - - -class Solution: - def isBalanced(self, root: TreeNode) -> bool: - def dfs(root): - if root is None: - return (True, 0) - l, ld = dfs(root.left) - r, rd = dfs(root.right) - d = max(ld, rd) + 1 - if l and r and abs(ld - rd) <= 1: - return (True, d) - return (False, d) - - return dfs(root)[0] -``` - - - - - diff --git "a/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/Solution2.py" deleted file mode 100644 index adbbaa03346c5..0000000000000 --- "a/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/Solution2.py" +++ /dev/null @@ -1,21 +0,0 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - - -class Solution: - def isBalanced(self, root: TreeNode) -> bool: - def dfs(root): - if root is None: - return (True, 0) - l, ld = dfs(root.left) - r, rd = dfs(root.right) - d = max(ld, rd) + 1 - if l and r and abs(ld - rd) <= 1: - return (True, d) - return (False, d) - - return dfs(root)[0] diff --git "a/lcof/\351\235\242\350\257\225\351\242\23056 - I. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23056 - I. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/README.md" index ad48541cad39b..84828af823293 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23056 - I. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23056 - I. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/README.md" @@ -51,7 +51,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9 对两个组分别进行异或运算,即可得到两个只出现一次的数字。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度。 +时间复杂度 $O(n)$,其中 $n$ 为数组长度。空间复杂度 $O(1)$。 diff --git "a/lcof/\351\235\242\350\257\225\351\242\23056 - II. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260 II/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23056 - II. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260 II/README.md" index 4bc932c2cc16c..43e176e618a64 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23056 - II. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260 II/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23056 - II. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260 II/README.md" @@ -48,7 +48,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9 我们用一个长度为 32 的数组 $cnt$ 来统计所有数字的每一位中 $1$ 的出现次数。如果某一位的 $1$ 的出现次数能被 $3$ 整除,那么那个只出现一次的数字二进制表示中对应的那一位也是 $0$;否则,那个只出现一次的数字二进制表示中对应的那一位是 $1$。 -时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 是数组的长度;而 $C$ 是整数的位数,本题中 $C=32$。 +时间复杂度 $O(n \times C)$,空间复杂度 $O(C)$。其中 $n$ 是数组的长度;而 $C$ 是整数的位数,本题中 $C=32$。 diff --git "a/lcof/\351\235\242\350\257\225\351\242\23057. \345\222\214\344\270\272s\347\232\204\344\270\244\344\270\252\346\225\260\345\255\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23057. \345\222\214\344\270\272s\347\232\204\344\270\244\344\270\252\346\225\260\345\255\227/README.md" index f12d498bd1af7..b7a03b2cbda09 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23057. \345\222\214\344\270\272s\347\232\204\344\270\244\344\270\252\346\225\260\345\255\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23057. \345\222\214\344\270\272s\347\232\204\344\270\244\344\270\252\346\225\260\345\255\227/README.md" @@ -37,15 +37,19 @@ edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9
  • 1 <= nums[i] <= 106
  • -**方法一:双指针** + + +## 解法 我们用双指针 $l$ 和 $r$ 分别指向数组的左右两端,然后不断移动指针,直到找到一组和为 $target$ 的连续正整数序列。 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组的长度。 - + + +### 方法一:双指针 -### **Python3** + #### Python3 @@ -62,8 +66,6 @@ class Solution: l += 1 ``` -### **Java** - #### Java ```java @@ -84,8 +86,6 @@ class Solution { } ``` -### **C++** - #### C++ ```cpp @@ -107,8 +107,6 @@ public: }; ``` -### **Go** - #### Go ```go @@ -127,8 +125,6 @@ func twoSum(nums []int, target int) []int { } ``` -### **JavaScript** - #### JavaScript ```js @@ -153,8 +149,6 @@ var twoSum = function (nums, target) { }; ``` -### **TypeScript** - #### TypeScript ```ts @@ -172,8 +166,6 @@ function twoSum(nums: number[], target: number): number[] { } ``` -### **Rust** - #### Rust ```rust @@ -200,189 +192,6 @@ impl Solution { } ``` -### **C#** - -#### C# - -```cs -public class Solution { - public int[] TwoSum(int[] nums, int target) { - int l = 0, r = nums.Length - 1; - while (true) { - if (nums[l] + nums[r] == target) { - return new int[] {nums[l], nums[r]}; - } - if (nums[l] + nums[r] > target) { - --r; - } else { - ++l; - } - } - } -} -``` - -### **...** - -``` - -``` - - - - - - - -## 解法 - - - -### 方法一 - - - -#### Python3 - -```python -class Solution: - def twoSum(self, nums: List[int], target: int) -> List[int]: - l, r = 0, len(nums) - 1 - while l < r: - if nums[l] + nums[r] == target: - return [nums[l], nums[r]] - if nums[l] + nums[r] > target: - r -= 1 - else: - l += 1 -``` - -#### Java - -```java -class Solution { - public int[] twoSum(int[] nums, int target) { - int l = 0, r = nums.length - 1; - while (true) { - if (nums[l] + nums[r] == target) { - return new int[] {nums[l], nums[r]}; - } - if (nums[l] + nums[r] > target) { - --r; - } else { - ++l; - } - } - } -} -``` - -#### C++ - -```cpp -class Solution { -public: - vector twoSum(vector& nums, int target) { - int l = 0, r = nums.size() - 1; - while (1) { - if (nums[l] + nums[r] == target) { - return {nums[l], nums[r]}; - } - if (nums[l] + nums[r] > target) { - --r; - } else { - ++l; - } - } - } -}; -``` - -#### Go - -```go -func twoSum(nums []int, target int) []int { - l, r := 0, len(nums)-1 - for { - if nums[l]+nums[r] == target { - return []int{nums[l], nums[r]} - } - if nums[l]+nums[r] > target { - r-- - } else { - l++ - } - } -} -``` - -#### TypeScript - -```ts -function twoSum(nums: number[], target: number): number[] { - let l = 0; - let r = nums.length - 1; - while (nums[l] + nums[r] !== target) { - if (nums[l] + nums[r] < target) { - l++; - } else { - r--; - } - } - return [nums[l], nums[r]]; -} -``` - -#### Rust - -```rust -use std::cmp::Ordering; - -impl Solution { - pub fn two_sum(nums: Vec, target: i32) -> Vec { - let mut l = 0; - let mut r = nums.len() - 1; - loop { - match target.cmp(&(nums[l] + nums[r])) { - Ordering::Less => { - r -= 1; - } - Ordering::Greater => { - l += 1; - } - Ordering::Equal => { - break vec![nums[l], nums[r]]; - } - } - } - } -} -``` - -#### JavaScript - -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number[]} - */ -var twoSum = function (nums, target) { - let l = 0; - let r = nums.length - 1; - while (1) { - if (nums[l] + nums[r] == target) { - return [nums[l], nums[r]]; - } - if (nums[l] + nums[r] > target) { - --r; - } else { - ++l; - } - } -}; -``` - #### C# ```cs diff --git a/solution/1600-1699/1673.Find the Most Competitive Subsequence/README.md b/solution/1600-1699/1673.Find the Most Competitive Subsequence/README.md index 0bf8e9f0c4eec..58ebfd5fa6154 100644 --- a/solution/1600-1699/1673.Find the Most Competitive Subsequence/README.md +++ b/solution/1600-1699/1673.Find the Most Competitive Subsequence/README.md @@ -155,7 +155,7 @@ function mostCompetitive(nums: number[], k: number): number[] { const stk: number[] = []; const n = nums.length; for (let i = 0; i < n; ++i) { - while (stk.length && stk.at(-1) > nums[i] && stk.length + n - i > k) { + while (stk.length && stk.at(-1)! > nums[i] && stk.length + n - i > k) { stk.pop(); } if (stk.length < k) { diff --git a/solution/1600-1699/1673.Find the Most Competitive Subsequence/README_EN.md b/solution/1600-1699/1673.Find the Most Competitive Subsequence/README_EN.md index 111d058e7b0f3..1a4b0826101b3 100644 --- a/solution/1600-1699/1673.Find the Most Competitive Subsequence/README_EN.md +++ b/solution/1600-1699/1673.Find the Most Competitive Subsequence/README_EN.md @@ -58,7 +58,13 @@ tags: -### Solution 1 +### Solution 1: Stack + +We traverse the array `nums` from left to right, maintaining a stack `stk`. During the traversal, if the current element `nums[i]` is less than the top element of the stack, and the number of elements in the stack plus $n-i$ is greater than $k$, then we pop the top element of the stack until the above condition is no longer satisfied. At this point, if the number of elements in the stack is less than $k$, then we push the current element into the stack. + +After the traversal, the elements in the stack are the answer. + +The time complexity is $O(n)$, and the space complexity is $O(k)$. Where $n$ is the length of the array `nums`. @@ -147,7 +153,7 @@ function mostCompetitive(nums: number[], k: number): number[] { const stk: number[] = []; const n = nums.length; for (let i = 0; i < n; ++i) { - while (stk.length && stk.at(-1) > nums[i] && stk.length + n - i > k) { + while (stk.length && stk.at(-1)! > nums[i] && stk.length + n - i > k) { stk.pop(); } if (stk.length < k) { diff --git a/solution/1600-1699/1673.Find the Most Competitive Subsequence/Solution.ts b/solution/1600-1699/1673.Find the Most Competitive Subsequence/Solution.ts index 3ba3ee00ee55d..3a0cf1a956c37 100644 --- a/solution/1600-1699/1673.Find the Most Competitive Subsequence/Solution.ts +++ b/solution/1600-1699/1673.Find the Most Competitive Subsequence/Solution.ts @@ -2,7 +2,7 @@ function mostCompetitive(nums: number[], k: number): number[] { const stk: number[] = []; const n = nums.length; for (let i = 0; i < n; ++i) { - while (stk.length && stk.at(-1) > nums[i] && stk.length + n - i > k) { + while (stk.length && stk.at(-1)! > nums[i] && stk.length + n - i > k) { stk.pop(); } if (stk.length < k) { From d6f5b96468b8fd709086c4a913494a5d40856fdf Mon Sep 17 00:00:00 2001 From: yanglbme Date: Fri, 24 May 2024 17:05:33 +0800 Subject: [PATCH 2/3] feat: add solutions to lc/lcof problems --- .../README.md" | 309 +++++++++--------- .../Solution.cpp" | 31 +- .../Solution.cs" | 31 +- .../Solution.go" | 31 +- .../Solution.java" | 22 +- .../Solution.js" | 11 - .../Solution.py" | 13 +- .../Solution.rs" | 26 +- .../Solution.ts" | 18 +- .../Solution2.cs" | 5 + .../Solution2.go" | 7 + .../Solution2.java" | 7 + .../Solution2.py" | 3 + .../Solution2.rs" | 6 +- .../Solution2.ts" | 16 +- .../Solution4.rs" | 32 -- .../0151.Reverse Words in a String/README.md | 182 ++++++++--- .../README_EN.md | 186 ++++++++--- .../Solution.cs | 27 +- .../Solution.go | 25 +- .../Solution.java | 17 +- .../Solution.py | 13 +- .../Solution.rs | 22 +- .../Solution.ts | 18 +- .../Solution2.cs | 5 + .../Solution2.go | 7 + .../Solution2.java | 27 +- .../Solution2.py | 17 +- .../Solution2.rs | 2 +- .../Solution2.ts | 3 + 30 files changed, 710 insertions(+), 409 deletions(-) delete mode 100644 "lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.js" create mode 100644 "lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.cs" create mode 100644 "lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.go" create mode 100644 "lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.java" create mode 100644 "lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.py" delete mode 100644 "lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution4.rs" create mode 100644 solution/0100-0199/0151.Reverse Words in a String/Solution2.cs create mode 100644 solution/0100-0199/0151.Reverse Words in a String/Solution2.go rename "lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution3.rs" => solution/0100-0199/0151.Reverse Words in a String/Solution2.rs (51%) create mode 100644 solution/0100-0199/0151.Reverse Words in a String/Solution2.ts diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/README.md" index 74cba777d6b6d..e01827d5c685a 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/README.md" @@ -56,11 +56,11 @@ edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9 -### 方法一:字符串分割 + 反转拼接 +### 方法一:双指针 -我们先去除字符串首尾的空格,然后将字符串按照空格分割成数组,再将数组反转,最后将数组拼接成以空格分割的字符串即可。 +我们可以使用双指针 $i$ 和 $j$,每次找到一个单词,将其添加到结果列表中,最后将结果列表反转,再拼接成字符串即可。 -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串长度。 +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。 @@ -69,7 +69,18 @@ edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9 ```python class Solution: def reverseWords(self, s: str) -> str: - return " ".join(s.strip().split()[::-1]) + words = [] + i, n = 0, len(s) + while i < n: + while i < n and s[i] == " ": + i += 1 + if i < n: + j = i + while j < n and s[j] != " ": + j += 1 + words.append(s[i:j]) + i = j + return " ".join(words[::-1]) ``` #### Java @@ -77,13 +88,23 @@ class Solution: ```java class Solution { public String reverseWords(String s) { - s = s.trim(); - var words = s.split("\\s+"); - for (int i = 0, j = words.length - 1; i < j; ++i, --j) { - var t = words[i]; - words[i] = words[j]; - words[j] = t; + List words = new ArrayList<>(); + int n = s.length(); + for (int i = 0; i < n;) { + while (i < n && s.charAt(i) == ' ') { + ++i; + } + if (i < n) { + StringBuilder t = new StringBuilder(); + int j = i; + while (j < n && s.charAt(j) != ' ') { + t.append(s.charAt(j++)); + } + words.add(t.toString()); + i = j; + } } + Collections.reverse(words); return String.join(" ", words); } } @@ -95,21 +116,28 @@ class Solution { class Solution { public: string reverseWords(string s) { - string res; - int i = s.size() - 1; - while (i >= 0) { - if (s[i] == ' ') { - i--; - } else { - int j = i; - while (i >= 0 && s[i] != ' ') { - i--; + int i = 0; + int j = 0; + int n = s.size(); + while (i < n) { + while (i < n && s[i] == ' ') { + ++i; + } + if (i < n) { + if (j != 0) { + s[j++] = ' '; } - res += s.substr(i + 1, j - i); - res.push_back(' '); + int k = i; + while (k < n && s[k] != ' ') { + s[j++] = s[k++]; + } + reverse(s.begin() + j - (k - i), s.begin() + j); + i = k; } } - return res.substr(0, res.size() - 1); + s.erase(s.begin() + j, s.end()); + reverse(s.begin(), s.end()); + return s; } }; ``` @@ -118,22 +146,27 @@ public: ```go func reverseWords(s string) string { - s = strings.Trim(s, " ") - n := len(s) - 1 - builder := new(strings.Builder) - for i, j := n, n; i >= 0; j = i { - for i >= 0 && s[i] != ' ' { - i-- - } - if builder.Len() != 0 { - builder.WriteRune(' ') + words := []string{} + i, n := 0, len(s) + for i < n { + for i < n && s[i] == ' ' { + i++ } - builder.WriteString(s[i+1 : j+1]) - for i >= 0 && s[i] == ' ' { - i-- + if i < n { + j := i + t := []byte{} + for j < n && s[j] != ' ' { + t = append(t, s[j]) + j++ + } + words = append(words, string(t)) + i = j } } - return builder.String() + for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 { + words[i], words[j] = words[j], words[i] + } + return strings.Join(words, " ") } ``` @@ -141,7 +174,23 @@ func reverseWords(s string) string { ```ts function reverseWords(s: string): string { - return s.trim().split(/\s+/).reverse().join(' '); + const words: string[] = []; + const n = s.length; + let i = 0; + while (i < n) { + while (i < n && s[i] === ' ') { + i++; + } + if (i < n) { + let j = i; + while (j < n && s[j] !== ' ') { + j++; + } + words.push(s.slice(i, j)); + i = j; + } + } + return words.reverse().join(' '); } ``` @@ -149,54 +198,55 @@ function reverseWords(s: string): string { ```rust impl Solution { - pub fn reverse_words(mut s: String) -> String { - let mut res = s.trim().split(' ').rev().collect::>(); - for i in (0..res.len()).rev() { - if res[i] == "" { - res.remove(i); + pub fn reverse_words(s: String) -> String { + let mut words = Vec::new(); + let s: Vec = s.chars().collect(); + let mut i = 0; + let n = s.len(); + + while i < n { + while i < n && s[i] == ' ' { + i += 1; + } + if i < n { + let mut j = i; + while j < n && s[j] != ' ' { + j += 1; + } + words.push(s[i..j].iter().collect::()); + i = j; } } - res.join(" ") + + words.reverse(); + words.join(" ") } } ``` -#### JavaScript - -```js -/** - * @param {string} s - * @return {string} - */ -var reverseWords = function (s) { - return s - .split(' ') - .reduce((acc, cur) => (cur !== '' ? acc.concat(cur) : acc), []) - .reverse() - .join(' '); -}; -``` - #### C# ```cs public class Solution { public string ReverseWords(string s) { - string[] tmp = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); - Stack ss = new Stack(); - string res = ""; - - foreach (var i in tmp) { - ss.Push(i); - } - - while (ss.Count > 0) { - res += ss.Pop(); - if (ss.Count > 0) { - res += " "; + List words = new List(); + int n = s.Length; + for (int i = 0; i < n;) { + while (i < n && s[i] == ' ') { + ++i; + } + if (i < n) { + System.Text.StringBuilder t = new System.Text.StringBuilder(); + int j = i; + while (j < n && s[j] != ' ') { + t.Append(s[j++]); + } + words.Add(t.ToString()); + i = j; } } - return res; + words.Reverse(); + return string.Join(" ", words); } } ``` @@ -205,111 +255,62 @@ public class Solution { - + -### 方法二 +### 方法二:字符串分割 + +我们可以使用语言内置的字符串分割函数,将字符串按空格分割成单词列表,然后将列表反转,再拼接成字符串即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。 -#### TypeScript +#### Python3 -```ts -function reverseWords(s: string): string { - s = s.trim(); - const res = []; - let l = s.length - 1; - let r = s.length - 1; - while (l >= 0) { - while (s[l] !== ' ' && l >= 0) { - l--; - } - res.push(s.substring(l + 1, r + 1)); - while (s[l] === ' ' && l >= 0) { - l--; - } - r = l; - } - return res.join(' '); -} +```python +class Solution: + def reverseWords(self, s: str) -> str: + return " ".join(reversed(s.split())) ``` -#### Rust +#### Java -```rust -impl Solution { - pub fn reverse_words(s: String) -> String { - s.split(' ') - .filter(|str| str != &"") - .rev() - .collect::>() - .join("") +```java +class Solution { + public String reverseWords(String s) { + List words = Arrays.asList(s.trim().split("\\s+")); + Collections.reverse(words); + return String.join(" ", words); } } ``` - - - - - - -### 方法三 - - - -#### Rust +#### Go -```rust -impl Solution { - pub fn reverse_words(s: String) -> String { - s.split_whitespace().rev().collect::>().join(" ") - } +```go +func reverseWords(s string) string { + words := strings.Fields(s) + for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 { + words[i], words[j] = words[j], words[i] + } + return strings.Join(words, " ") } ``` - - - - - - -### 方法四 +#### TypeScript - +```ts +function reverseWords(s: string): string { + return s.trim().split(/\s+/).reverse().join(' '); +} +``` #### Rust ```rust impl Solution { - pub fn reverse_words(mut s: String) -> String { - s = s.trim().to_string(); - // 添加辅助空格,防止 usize 破界 - s.insert_str(0, " "); - let chars = s.chars().collect::>(); - let mut res = vec![]; - let mut l = chars.len() - 1; - let mut r = chars.len() - 1; - while l > 0 { - while chars[l] == ' ' { - if l == 0 { - break; - } - l -= 1; - } - r = l; - while chars[l] != ' ' { - if l == 0 { - break; - } - l -= 1; - } - let mut str = String::new(); - for i in l + 1..r + 1 { - str.push(chars[i]); - } - res.push(str); - } - res.join(" ") + pub fn reverse_words(s: String) -> String { + s.split_whitespace().rev().collect::>().join(" ") } } ``` diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.cpp" index fe8efc467a721..e5b8aa83cb46e 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.cpp" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.cpp" @@ -1,20 +1,27 @@ class Solution { public: string reverseWords(string s) { - string res; - int i = s.size() - 1; - while (i >= 0) { - if (s[i] == ' ') { - i--; - } else { - int j = i; - while (i >= 0 && s[i] != ' ') { - i--; + int i = 0; + int j = 0; + int n = s.size(); + while (i < n) { + while (i < n && s[i] == ' ') { + ++i; + } + if (i < n) { + if (j != 0) { + s[j++] = ' '; + } + int k = i; + while (k < n && s[k] != ' ') { + s[j++] = s[k++]; } - res += s.substr(i + 1, j - i); - res.push_back(' '); + reverse(s.begin() + j - (k - i), s.begin() + j); + i = k; } } - return res.substr(0, res.size() - 1); + s.erase(s.begin() + j, s.end()); + reverse(s.begin(), s.end()); + return s; } }; \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.cs" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.cs" index 4c90180b3fc7b..72445d803589c 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.cs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.cs" @@ -1,19 +1,22 @@ public class Solution { public string ReverseWords(string s) { - string[] tmp = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); - Stack ss = new Stack(); - string res = ""; - - foreach (var i in tmp) { - ss.Push(i); - } - - while (ss.Count > 0) { - res += ss.Pop(); - if (ss.Count > 0) { - res += " "; + List words = new List(); + int n = s.Length; + for (int i = 0; i < n;) { + while (i < n && s[i] == ' ') { + ++i; + } + if (i < n) { + System.Text.StringBuilder t = new System.Text.StringBuilder(); + int j = i; + while (j < n && s[j] != ' ') { + t.Append(s[j++]); + } + words.Add(t.ToString()); + i = j; } } - return res; + words.Reverse(); + return string.Join(" ", words); } -} +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.go" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.go" index 4996fba9e7a5b..2cc28c36f45a5 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.go" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.go" @@ -1,18 +1,23 @@ func reverseWords(s string) string { - s = strings.Trim(s, " ") - n := len(s) - 1 - builder := new(strings.Builder) - for i, j := n, n; i >= 0; j = i { - for i >= 0 && s[i] != ' ' { - i-- + words := []string{} + i, n := 0, len(s) + for i < n { + for i < n && s[i] == ' ' { + i++ } - if builder.Len() != 0 { - builder.WriteRune(' ') - } - builder.WriteString(s[i+1 : j+1]) - for i >= 0 && s[i] == ' ' { - i-- + if i < n { + j := i + t := []byte{} + for j < n && s[j] != ' ' { + t = append(t, s[j]) + j++ + } + words = append(words, string(t)) + i = j } } - return builder.String() + for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 { + words[i], words[j] = words[j], words[i] + } + return strings.Join(words, " ") } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.java" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.java" index b5145421a48e4..627a77c0dacab 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.java" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.java" @@ -1,12 +1,22 @@ class Solution { public String reverseWords(String s) { - s = s.trim(); - var words = s.split("\\s+"); - for (int i = 0, j = words.length - 1; i < j; ++i, --j) { - var t = words[i]; - words[i] = words[j]; - words[j] = t; + List words = new ArrayList<>(); + int n = s.length(); + for (int i = 0; i < n;) { + while (i < n && s.charAt(i) == ' ') { + ++i; + } + if (i < n) { + StringBuilder t = new StringBuilder(); + int j = i; + while (j < n && s.charAt(j) != ' ') { + t.append(s.charAt(j++)); + } + words.add(t.toString()); + i = j; + } } + Collections.reverse(words); return String.join(" ", words); } } \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.js" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.js" deleted file mode 100644 index 1f8c4de652926..0000000000000 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.js" +++ /dev/null @@ -1,11 +0,0 @@ -/** - * @param {string} s - * @return {string} - */ -var reverseWords = function (s) { - return s - .split(' ') - .reduce((acc, cur) => (cur !== '' ? acc.concat(cur) : acc), []) - .reverse() - .join(' '); -}; diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.py" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.py" index 7f0c901f03f17..bc595b70db61c 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.py" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.py" @@ -1,3 +1,14 @@ class Solution: def reverseWords(self, s: str) -> str: - return " ".join(s.strip().split()[::-1]) + words = [] + i, n = 0, len(s) + while i < n: + while i < n and s[i] == " ": + i += 1 + if i < n: + j = i + while j < n and s[j] != " ": + j += 1 + words.append(s[i:j]) + i = j + return " ".join(words[::-1]) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.rs" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.rs" index c0df6a4e36143..cd2410e49a76c 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.rs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.rs" @@ -1,11 +1,25 @@ impl Solution { - pub fn reverse_words(mut s: String) -> String { - let mut res = s.trim().split(' ').rev().collect::>(); - for i in (0..res.len()).rev() { - if res[i] == "" { - res.remove(i); + pub fn reverse_words(s: String) -> String { + let mut words = Vec::new(); + let s: Vec = s.chars().collect(); + let mut i = 0; + let n = s.len(); + + while i < n { + while i < n && s[i] == ' ' { + i += 1; + } + if i < n { + let mut j = i; + while j < n && s[j] != ' ' { + j += 1; + } + words.push(s[i..j].iter().collect::()); + i = j; } } - res.join(" ") + + words.reverse(); + words.join(" ") } } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.ts" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.ts" index b4f1045ea13bc..b7e1571533c5f 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.ts" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution.ts" @@ -1,3 +1,19 @@ function reverseWords(s: string): string { - return s.trim().split(/\s+/).reverse().join(' '); + const words: string[] = []; + const n = s.length; + let i = 0; + while (i < n) { + while (i < n && s[i] === ' ') { + i++; + } + if (i < n) { + let j = i; + while (j < n && s[j] !== ' ') { + j++; + } + words.push(s.slice(i, j)); + i = j; + } + } + return words.reverse().join(' '); } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.cs" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.cs" new file mode 100644 index 0000000000000..6aefaa604e775 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.cs" @@ -0,0 +1,5 @@ +public class Solution { + public string ReverseWords(string s) { + return string.Join(" ", s.Trim().Split(" ").Where(word => !string.IsNullOrEmpty(word) && !string.IsNullOrEmpty(word.Trim())).Reverse()); + } +} diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.go" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.go" new file mode 100644 index 0000000000000..b58009eb305c5 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.go" @@ -0,0 +1,7 @@ +func reverseWords(s string) string { + words := strings.Fields(s) + for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 { + words[i], words[j] = words[j], words[i] + } + return strings.Join(words, " ") +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.java" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.java" new file mode 100644 index 0000000000000..9a59b830e4171 --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.java" @@ -0,0 +1,7 @@ +class Solution { + public String reverseWords(String s) { + List words = Arrays.asList(s.trim().split("\\s+")); + Collections.reverse(words); + return String.join(" ", words); + } +} \ No newline at end of file diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.py" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.py" new file mode 100644 index 0000000000000..afdb23c10b83c --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.py" @@ -0,0 +1,3 @@ +class Solution: + def reverseWords(self, s: str) -> str: + return " ".join(reversed(s.split())) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.rs" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.rs" index 2cbefc51d68a2..c7aeae5eb369d 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.rs" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.rs" @@ -1,9 +1,5 @@ impl Solution { pub fn reverse_words(s: String) -> String { - s.split(' ') - .filter(|str| str != &"") - .rev() - .collect::>() - .join("") + s.split_whitespace().rev().collect::>().join(" ") } } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.ts" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.ts" index 5645865765f1f..b4f1045ea13bc 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.ts" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution2.ts" @@ -1,17 +1,3 @@ function reverseWords(s: string): string { - s = s.trim(); - const res = []; - let l = s.length - 1; - let r = s.length - 1; - while (l >= 0) { - while (s[l] !== ' ' && l >= 0) { - l--; - } - res.push(s.substring(l + 1, r + 1)); - while (s[l] === ' ' && l >= 0) { - l--; - } - r = l; - } - return res.join(' '); + return s.trim().split(/\s+/).reverse().join(' '); } diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution4.rs" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution4.rs" deleted file mode 100644 index a8dac78a3dac7..0000000000000 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution4.rs" +++ /dev/null @@ -1,32 +0,0 @@ -impl Solution { - pub fn reverse_words(mut s: String) -> String { - s = s.trim().to_string(); - // 添加辅助空格,防止 usize 破界 - s.insert_str(0, " "); - let chars = s.chars().collect::>(); - let mut res = vec![]; - let mut l = chars.len() - 1; - let mut r = chars.len() - 1; - while l > 0 { - while chars[l] == ' ' { - if l == 0 { - break; - } - l -= 1; - } - r = l; - while chars[l] != ' ' { - if l == 0 { - break; - } - l -= 1; - } - let mut str = String::new(); - for i in l + 1..r + 1 { - str.push(chars[i]); - } - res.push(str); - } - res.join(" ") - } -} diff --git a/solution/0100-0199/0151.Reverse Words in a String/README.md b/solution/0100-0199/0151.Reverse Words in a String/README.md index 331a9809651f6..a9f579ee7c1d0 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/README.md +++ b/solution/0100-0199/0151.Reverse Words in a String/README.md @@ -73,9 +73,9 @@ tags: -### 方法一:使用语言自带的函数 +### 方法一:双指针 -我们将字符串按照空格分割成字符串列表,然后将列表反转,最后将列表拼接成以空格分割的字符串即可。 +我们可以使用双指针 $i$ 和 $j$,每次找到一个单词,将其添加到结果列表中,最后将结果列表反转,再拼接成字符串即可。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。 @@ -86,7 +86,18 @@ tags: ```python class Solution: def reverseWords(self, s: str) -> str: - return ' '.join(reversed(s.split())) + words = [] + i, n = 0, len(s) + while i < n: + while i < n and s[i] == " ": + i += 1 + if i < n: + j = i + while j < n and s[j] != " ": + j += 1 + words.append(s[i:j]) + i = j + return " ".join(words[::-1]) ``` #### Java @@ -94,7 +105,22 @@ class Solution: ```java class Solution { public String reverseWords(String s) { - List words = Arrays.asList(s.trim().split("\\s+")); + List words = new ArrayList<>(); + int n = s.length(); + for (int i = 0; i < n;) { + while (i < n && s.charAt(i) == ' ') { + ++i; + } + if (i < n) { + StringBuilder t = new StringBuilder(); + int j = i; + while (j < n && s.charAt(j) != ' ') { + t.append(s.charAt(j++)); + } + words.add(t.toString()); + i = j; + } + } Collections.reverse(words); return String.join(" ", words); } @@ -137,14 +163,27 @@ public: ```go func reverseWords(s string) string { - words := strings.Split(s, " ") - var ans []string - for i := len(words) - 1; i >= 0; i-- { - if words[i] != "" { - ans = append(ans, words[i]) + words := []string{} + i, n := 0, len(s) + for i < n { + for i < n && s[i] == ' ' { + i++ } + if i < n { + j := i + t := []byte{} + for j < n && s[j] != ' ' { + t = append(t, s[j]) + j++ + } + words = append(words, string(t)) + i = j + } + } + for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 { + words[i], words[j] = words[j], words[i] } - return strings.Join(ans, " ") + return strings.Join(words, " ") } ``` @@ -152,7 +191,23 @@ func reverseWords(s string) string { ```ts function reverseWords(s: string): string { - return s.trim().split(/\s+/).reverse().join(' '); + const words: string[] = []; + const n = s.length; + let i = 0; + while (i < n) { + while (i < n && s[i] === ' ') { + i++; + } + if (i < n) { + let j = i; + while (j < n && s[j] !== ' ') { + j++; + } + words.push(s.slice(i, j)); + i = j; + } + } + return words.reverse().join(' '); } ``` @@ -161,7 +216,27 @@ function reverseWords(s: string): string { ```rust impl Solution { pub fn reverse_words(s: String) -> String { - s.split_whitespace().rev().collect::>().join(" ") + let mut words = Vec::new(); + let s: Vec = s.chars().collect(); + let mut i = 0; + let n = s.len(); + + while i < n { + while i < n && s[i] == ' ' { + i += 1; + } + if i < n { + let mut j = i; + while j < n && s[j] != ' ' { + j += 1; + } + words.push(s[i..j].iter().collect::()); + i = j; + } + } + + words.reverse(); + words.join(" ") } } ``` @@ -171,7 +246,24 @@ impl Solution { ```cs public class Solution { public string ReverseWords(string s) { - return string.Join(" ", s.Trim().Split(" ").Where(word => !string.IsNullOrEmpty(word) && !string.IsNullOrEmpty(word.Trim())).Reverse()); + List words = new List(); + int n = s.Length; + for (int i = 0; i < n;) { + while (i < n && s[i] == ' ') { + ++i; + } + if (i < n) { + System.Text.StringBuilder t = new System.Text.StringBuilder(); + int j = i; + while (j < n && s[j] != ' ') { + t.Append(s[j++]); + } + words.Add(t.ToString()); + i = j; + } + } + words.Reverse(); + return string.Join(" ", words); } } ``` @@ -182,9 +274,9 @@ public class Solution { -### 方法二:双指针 +### 方法二:字符串分割 -我们可以使用双指针 $i$ 和 $j$,每次找到一个单词,将其添加到结果列表中,最后将结果列表反转,再拼接成字符串即可。 +我们可以使用语言内置的字符串分割函数,将字符串按空格分割成单词列表,然后将列表反转,再拼接成字符串即可。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。 @@ -195,18 +287,7 @@ public class Solution { ```python class Solution: def reverseWords(self, s: str) -> str: - ans = [] - i, n = 0, len(s) - while i < n: - while i < n and s[i] == ' ': - i += 1 - if i < n: - j = i - while j < n and s[j] != ' ': - j += 1 - ans.append(s[i:j]) - i = j - return ' '.join(ans[::-1]) + return " ".join(reversed(s.split())) ``` #### Java @@ -214,28 +295,43 @@ class Solution: ```java class Solution { public String reverseWords(String s) { - List words = new ArrayList<>(); - int n = s.length(); - for (int i = 0; i < n;) { - while (i < n && s.charAt(i) == ' ') { - ++i; - } - if (i < n) { - StringBuilder t = new StringBuilder(); - int j = i; - while (j < n && s.charAt(j) != ' ') { - t.append(s.charAt(j++)); - } - words.add(t.toString()); - i = j; - } - } + List words = Arrays.asList(s.trim().split("\\s+")); Collections.reverse(words); return String.join(" ", words); } } ``` +#### Go + +```go +func reverseWords(s string) string { + words := strings.Fields(s) + for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 { + words[i], words[j] = words[j], words[i] + } + return strings.Join(words, " ") +} +``` + +#### TypeScript + +```ts +function reverseWords(s: string): string { + return s.trim().split(/\s+/).reverse().join(' '); +} +``` + +#### Rust + +```rust +impl Solution { + pub fn reverse_words(s: String) -> String { + s.split_whitespace().rev().collect::>().join(" ") + } +} +``` + diff --git a/solution/0100-0199/0151.Reverse Words in a String/README_EN.md b/solution/0100-0199/0151.Reverse Words in a String/README_EN.md index 9b57630e98af2..9cbdf2263c034 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/README_EN.md +++ b/solution/0100-0199/0151.Reverse Words in a String/README_EN.md @@ -67,11 +67,11 @@ tags: -### Solution 1: Use Language Built-in Functions +### Solution 1: Two Pointers -We split the string into a list of strings by spaces, then reverse the list, and finally join the list into a string separated by spaces. +We can use two pointers $i$ and $j$ to find each word, add it to the result list, then reverse the result list, and finally concatenate it into a string. -Time complexity $O(n)$, space complexity $O(n)$, where $n$ is the length of the string. +The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string. @@ -80,7 +80,18 @@ Time complexity $O(n)$, space complexity $O(n)$, where $n$ is the length of the ```python class Solution: def reverseWords(self, s: str) -> str: - return ' '.join(reversed(s.split())) + words = [] + i, n = 0, len(s) + while i < n: + while i < n and s[i] == " ": + i += 1 + if i < n: + j = i + while j < n and s[j] != " ": + j += 1 + words.append(s[i:j]) + i = j + return " ".join(words[::-1]) ``` #### Java @@ -88,7 +99,22 @@ class Solution: ```java class Solution { public String reverseWords(String s) { - List words = Arrays.asList(s.trim().split("\\s+")); + List words = new ArrayList<>(); + int n = s.length(); + for (int i = 0; i < n;) { + while (i < n && s.charAt(i) == ' ') { + ++i; + } + if (i < n) { + StringBuilder t = new StringBuilder(); + int j = i; + while (j < n && s.charAt(j) != ' ') { + t.append(s.charAt(j++)); + } + words.add(t.toString()); + i = j; + } + } Collections.reverse(words); return String.join(" ", words); } @@ -131,14 +157,27 @@ public: ```go func reverseWords(s string) string { - words := strings.Split(s, " ") - var ans []string - for i := len(words) - 1; i >= 0; i-- { - if words[i] != "" { - ans = append(ans, words[i]) + words := []string{} + i, n := 0, len(s) + for i < n { + for i < n && s[i] == ' ' { + i++ + } + if i < n { + j := i + t := []byte{} + for j < n && s[j] != ' ' { + t = append(t, s[j]) + j++ + } + words = append(words, string(t)) + i = j } } - return strings.Join(ans, " ") + for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 { + words[i], words[j] = words[j], words[i] + } + return strings.Join(words, " ") } ``` @@ -146,7 +185,23 @@ func reverseWords(s string) string { ```ts function reverseWords(s: string): string { - return s.trim().split(/\s+/).reverse().join(' '); + const words: string[] = []; + const n = s.length; + let i = 0; + while (i < n) { + while (i < n && s[i] === ' ') { + i++; + } + if (i < n) { + let j = i; + while (j < n && s[j] !== ' ') { + j++; + } + words.push(s.slice(i, j)); + i = j; + } + } + return words.reverse().join(' '); } ``` @@ -155,7 +210,27 @@ function reverseWords(s: string): string { ```rust impl Solution { pub fn reverse_words(s: String) -> String { - s.split_whitespace().rev().collect::>().join(" ") + let mut words = Vec::new(); + let s: Vec = s.chars().collect(); + let mut i = 0; + let n = s.len(); + + while i < n { + while i < n && s[i] == ' ' { + i += 1; + } + if i < n { + let mut j = i; + while j < n && s[j] != ' ' { + j += 1; + } + words.push(s[i..j].iter().collect::()); + i = j; + } + } + + words.reverse(); + words.join(" ") } } ``` @@ -165,7 +240,24 @@ impl Solution { ```cs public class Solution { public string ReverseWords(string s) { - return string.Join(" ", s.Trim().Split(" ").Where(word => !string.IsNullOrEmpty(word) && !string.IsNullOrEmpty(word.Trim())).Reverse()); + List words = new List(); + int n = s.Length; + for (int i = 0; i < n;) { + while (i < n && s[i] == ' ') { + ++i; + } + if (i < n) { + System.Text.StringBuilder t = new System.Text.StringBuilder(); + int j = i; + while (j < n && s[j] != ' ') { + t.Append(s[j++]); + } + words.Add(t.ToString()); + i = j; + } + } + words.Reverse(); + return string.Join(" ", words); } } ``` @@ -176,11 +268,11 @@ public class Solution { -### Solution 2: Two Pointers +### Solution 2: String Split -We can use two pointers $i$ and $j$, each time we find a word, add it to the result list, then reverse the result list, and finally join the list into a string. +We can use the built-in string split function to split the string into a list of words by spaces, then reverse the list, and finally concatenate it into a string. -Time complexity $O(n)$, space complexity $O(n)$, where $n$ is the length of the string. +The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string. @@ -189,18 +281,7 @@ Time complexity $O(n)$, space complexity $O(n)$, where $n$ is the length of the ```python class Solution: def reverseWords(self, s: str) -> str: - ans = [] - i, n = 0, len(s) - while i < n: - while i < n and s[i] == ' ': - i += 1 - if i < n: - j = i - while j < n and s[j] != ' ': - j += 1 - ans.append(s[i:j]) - i = j - return ' '.join(ans[::-1]) + return " ".join(reversed(s.split())) ``` #### Java @@ -208,28 +289,43 @@ class Solution: ```java class Solution { public String reverseWords(String s) { - List words = new ArrayList<>(); - int n = s.length(); - for (int i = 0; i < n;) { - while (i < n && s.charAt(i) == ' ') { - ++i; - } - if (i < n) { - StringBuilder t = new StringBuilder(); - int j = i; - while (j < n && s.charAt(j) != ' ') { - t.append(s.charAt(j++)); - } - words.add(t.toString()); - i = j; - } - } + List words = Arrays.asList(s.trim().split("\\s+")); Collections.reverse(words); return String.join(" ", words); } } ``` +#### Go + +```go +func reverseWords(s string) string { + words := strings.Fields(s) + for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 { + words[i], words[j] = words[j], words[i] + } + return strings.Join(words, " ") +} +``` + +#### TypeScript + +```ts +function reverseWords(s: string): string { + return s.trim().split(/\s+/).reverse().join(' '); +} +``` + +#### Rust + +```rust +impl Solution { + pub fn reverse_words(s: String) -> String { + s.split_whitespace().rev().collect::>().join(" ") + } +} +``` + diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution.cs b/solution/0100-0199/0151.Reverse Words in a String/Solution.cs index 6aefaa604e775..833918b08a788 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/Solution.cs +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution.cs @@ -1,5 +1,22 @@ -public class Solution { - public string ReverseWords(string s) { - return string.Join(" ", s.Trim().Split(" ").Where(word => !string.IsNullOrEmpty(word) && !string.IsNullOrEmpty(word.Trim())).Reverse()); - } -} +public class Solution { + public string ReverseWords(string s) { + List words = new List(); + int n = s.Length; + for (int i = 0; i < n;) { + while (i < n && s[i] == ' ') { + ++i; + } + if (i < n) { + System.Text.StringBuilder t = new System.Text.StringBuilder(); + int j = i; + while (j < n && s[j] != ' ') { + t.Append(s[j++]); + } + words.Add(t.ToString()); + i = j; + } + } + words.Reverse(); + return string.Join(" ", words); + } +} \ No newline at end of file diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution.go b/solution/0100-0199/0151.Reverse Words in a String/Solution.go index 4cdaef3af1d66..2cc28c36f45a5 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/Solution.go +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution.go @@ -1,10 +1,23 @@ func reverseWords(s string) string { - words := strings.Split(s, " ") - var ans []string - for i := len(words) - 1; i >= 0; i-- { - if words[i] != "" { - ans = append(ans, words[i]) + words := []string{} + i, n := 0, len(s) + for i < n { + for i < n && s[i] == ' ' { + i++ } + if i < n { + j := i + t := []byte{} + for j < n && s[j] != ' ' { + t = append(t, s[j]) + j++ + } + words = append(words, string(t)) + i = j + } + } + for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 { + words[i], words[j] = words[j], words[i] } - return strings.Join(ans, " ") + return strings.Join(words, " ") } \ No newline at end of file diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution.java b/solution/0100-0199/0151.Reverse Words in a String/Solution.java index 5f6ace9968f40..627a77c0dacab 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/Solution.java +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution.java @@ -1,6 +1,21 @@ class Solution { public String reverseWords(String s) { - List words = Arrays.asList(s.trim().split("\\s+")); + List words = new ArrayList<>(); + int n = s.length(); + for (int i = 0; i < n;) { + while (i < n && s.charAt(i) == ' ') { + ++i; + } + if (i < n) { + StringBuilder t = new StringBuilder(); + int j = i; + while (j < n && s.charAt(j) != ' ') { + t.append(s.charAt(j++)); + } + words.add(t.toString()); + i = j; + } + } Collections.reverse(words); return String.join(" ", words); } diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution.py b/solution/0100-0199/0151.Reverse Words in a String/Solution.py index b929f3e9e455b..bc595b70db61c 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/Solution.py +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution.py @@ -1,3 +1,14 @@ class Solution: def reverseWords(self, s: str) -> str: - return ' '.join(reversed(s.split())) + words = [] + i, n = 0, len(s) + while i < n: + while i < n and s[i] == " ": + i += 1 + if i < n: + j = i + while j < n and s[j] != " ": + j += 1 + words.append(s[i:j]) + i = j + return " ".join(words[::-1]) diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution.rs b/solution/0100-0199/0151.Reverse Words in a String/Solution.rs index c7aeae5eb369d..cd2410e49a76c 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/Solution.rs +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution.rs @@ -1,5 +1,25 @@ impl Solution { pub fn reverse_words(s: String) -> String { - s.split_whitespace().rev().collect::>().join(" ") + let mut words = Vec::new(); + let s: Vec = s.chars().collect(); + let mut i = 0; + let n = s.len(); + + while i < n { + while i < n && s[i] == ' ' { + i += 1; + } + if i < n { + let mut j = i; + while j < n && s[j] != ' ' { + j += 1; + } + words.push(s[i..j].iter().collect::()); + i = j; + } + } + + words.reverse(); + words.join(" ") } } diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution.ts b/solution/0100-0199/0151.Reverse Words in a String/Solution.ts index b4f1045ea13bc..b7e1571533c5f 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/Solution.ts +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution.ts @@ -1,3 +1,19 @@ function reverseWords(s: string): string { - return s.trim().split(/\s+/).reverse().join(' '); + const words: string[] = []; + const n = s.length; + let i = 0; + while (i < n) { + while (i < n && s[i] === ' ') { + i++; + } + if (i < n) { + let j = i; + while (j < n && s[j] !== ' ') { + j++; + } + words.push(s.slice(i, j)); + i = j; + } + } + return words.reverse().join(' '); } diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution2.cs b/solution/0100-0199/0151.Reverse Words in a String/Solution2.cs new file mode 100644 index 0000000000000..58d73c251003d --- /dev/null +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution2.cs @@ -0,0 +1,5 @@ +public class Solution { + public string ReverseWords(string s) { + return string.Join(" ", s.Trim().Split(" ").Where(word => !string.IsNullOrEmpty(word) && !string.IsNullOrEmpty(word.Trim())).Reverse()); + } +} diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution2.go b/solution/0100-0199/0151.Reverse Words in a String/Solution2.go new file mode 100644 index 0000000000000..b58009eb305c5 --- /dev/null +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution2.go @@ -0,0 +1,7 @@ +func reverseWords(s string) string { + words := strings.Fields(s) + for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 { + words[i], words[j] = words[j], words[i] + } + return strings.Join(words, " ") +} \ No newline at end of file diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution2.java b/solution/0100-0199/0151.Reverse Words in a String/Solution2.java index 627a77c0dacab..9a59b830e4171 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/Solution2.java +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution2.java @@ -1,22 +1,7 @@ -class Solution { - public String reverseWords(String s) { - List words = new ArrayList<>(); - int n = s.length(); - for (int i = 0; i < n;) { - while (i < n && s.charAt(i) == ' ') { - ++i; - } - if (i < n) { - StringBuilder t = new StringBuilder(); - int j = i; - while (j < n && s.charAt(j) != ' ') { - t.append(s.charAt(j++)); - } - words.add(t.toString()); - i = j; - } - } - Collections.reverse(words); - return String.join(" ", words); - } +class Solution { + public String reverseWords(String s) { + List words = Arrays.asList(s.trim().split("\\s+")); + Collections.reverse(words); + return String.join(" ", words); + } } \ No newline at end of file diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution2.py b/solution/0100-0199/0151.Reverse Words in a String/Solution2.py index 70729dcff4fd5..afdb23c10b83c 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/Solution2.py +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution2.py @@ -1,14 +1,3 @@ -class Solution: - def reverseWords(self, s: str) -> str: - ans = [] - i, n = 0, len(s) - while i < n: - while i < n and s[i] == ' ': - i += 1 - if i < n: - j = i - while j < n and s[j] != ' ': - j += 1 - ans.append(s[i:j]) - i = j - return ' '.join(ans[::-1]) +class Solution: + def reverseWords(self, s: str) -> str: + return " ".join(reversed(s.split())) diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution3.rs" b/solution/0100-0199/0151.Reverse Words in a String/Solution2.rs similarity index 51% rename from "lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution3.rs" rename to solution/0100-0199/0151.Reverse Words in a String/Solution2.rs index 8e244b2222f04..c7aeae5eb369d 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/Solution3.rs" +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution2.rs @@ -1,5 +1,5 @@ impl Solution { pub fn reverse_words(s: String) -> String { - s.split_whitespace().rev().collect::>().join(" ") + s.split_whitespace().rev().collect::>().join(" ") } } diff --git a/solution/0100-0199/0151.Reverse Words in a String/Solution2.ts b/solution/0100-0199/0151.Reverse Words in a String/Solution2.ts new file mode 100644 index 0000000000000..b4f1045ea13bc --- /dev/null +++ b/solution/0100-0199/0151.Reverse Words in a String/Solution2.ts @@ -0,0 +1,3 @@ +function reverseWords(s: string): string { + return s.trim().split(/\s+/).reverse().join(' '); +} From 37429564dfef80eed78a398ce99724a6a85d251c Mon Sep 17 00:00:00 2001 From: yanglbme Date: Fri, 24 May 2024 17:07:27 +0800 Subject: [PATCH 3/3] fix: update --- .../README.md" | 24 ------------------- .../Solution2.cpp" | 9 ------- 2 files changed, 33 deletions(-) delete mode 100644 "lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution2.cpp" diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/README.md" index 763d8821f9130..5034a86ec2a78 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/README.md" @@ -125,28 +125,4 @@ public class Solution { - - -### 方法二 - - - -#### C++ - -```cpp -class Solution { -public: - string reverseLeftWords(string s, int n) { - reverse(s.begin(), s.begin() + n); - reverse(s.begin() + n, s.end()); - reverse(s.begin(), s.end()); - return s; - } -}; -``` - - - - - diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution2.cpp" "b/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution2.cpp" deleted file mode 100644 index cc632130155b1..0000000000000 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/Solution2.cpp" +++ /dev/null @@ -1,9 +0,0 @@ -class Solution { -public: - string reverseLeftWords(string s, int n) { - reverse(s.begin(), s.begin() + n); - reverse(s.begin() + n, s.end()); - reverse(s.begin(), s.end()); - return s; - } -}; \ No newline at end of file