diff --git a/solution/0100-0199/0170.Two Sum III - Data structure design/README.md b/solution/0100-0199/0170.Two Sum III - Data structure design/README.md index 1944f539dc0b2..8c07424e69231 100644 --- a/solution/0100-0199/0170.Two Sum III - Data structure design/README.md +++ b/solution/0100-0199/0170.Two Sum III - Data structure design/README.md @@ -68,8 +68,9 @@ twoSum.find(7); // 没有两个整数加起来等于 7 ,返回 false ```python class TwoSum: + def __init__(self): - self.cnt = Counter() + self.cnt = defaultdict(int) def add(self, number: int) -> None: self.cnt[number] += 1 @@ -77,9 +78,8 @@ class TwoSum: def find(self, value: int) -> bool: for x, v in self.cnt.items(): y = value - x - if y in self.cnt: - if x != y or v > 1: - return True + if y in self.cnt and (x != y or v > 1): + return True return False @@ -104,10 +104,8 @@ class TwoSum { for (var e : cnt.entrySet()) { int x = e.getKey(), v = e.getValue(); int y = value - x; - if (cnt.containsKey(y)) { - if (x != y || v > 1) { - return true; - } + if (cnt.containsKey(y) && (x != y || v > 1)) { + return true; } } return false; @@ -135,10 +133,8 @@ public: bool find(int value) { for (auto& [x, v] : cnt) { long y = (long) value - x; - if (cnt.count(y)) { - if (x != y || v > 1) { - return true; - } + if (cnt.contains(y) && (x != y || v > 1)) { + return true; } } return false; @@ -166,7 +162,7 @@ func Constructor() TwoSum { } func (this *TwoSum) Add(number int) { - this.cnt[number]++ + this.cnt[number] += 1 } func (this *TwoSum) Find(value int) bool { @@ -187,6 +183,34 @@ func (this *TwoSum) Find(value int) bool { */ ``` +```ts +class TwoSum { + private cnt: Map = new Map(); + constructor() {} + + add(number: number): void { + this.cnt.set(number, (this.cnt.get(number) || 0) + 1); + } + + find(value: number): boolean { + for (const [x, v] of this.cnt) { + const y = value - x; + if (this.cnt.has(y) && (x !== y || v > 1)) { + return true; + } + } + return false; + } +} + +/** + * Your TwoSum object will be instantiated and called as such: + * var obj = new TwoSum() + * obj.add(number) + * var param_2 = obj.find(value) + */ +``` + diff --git a/solution/0100-0199/0170.Two Sum III - Data structure design/README_EN.md b/solution/0100-0199/0170.Two Sum III - Data structure design/README_EN.md index 2006b5eede565..81a1b801402eb 100644 --- a/solution/0100-0199/0170.Two Sum III - Data structure design/README_EN.md +++ b/solution/0100-0199/0170.Two Sum III - Data structure design/README_EN.md @@ -46,14 +46,28 @@ twoSum.find(7); // No two integers sum up to 7, return false ## Solutions -### Solution 1 +### Solution 1: Hash Table + +We use a hash table `cnt` to store the count of each number. + +When the `add` method is called, we increment the count of the number `number`. + +When the `find` method is called, we iterate over the hash table `cnt`. For each key `x`, we check if `value - x` is also a key in the hash table `cnt`. If it is, we check if `x` is equal to `value - x`. If they are not equal, it means we have found a pair of numbers whose sum is `value`, and we return `true`. If they are equal, we check if the count of `x` is greater than `1`. If it is, it means we have found a pair of numbers whose sum is `value`, and we return `true`. If it is less than or equal to `1`, it means we have not found a pair of numbers whose sum is `value`, and we continue to iterate over the hash table `cnt`. If we have not found a pair after the iteration, we return `false`. + +Time complexity: + +- The time complexity of the `add` method is $O(1)$. +- The time complexity of the `find` method is $O(n)$. + +Space complexity is $O(n)$, where $n$ is the size of the hash table `cnt`. ```python class TwoSum: + def __init__(self): - self.cnt = Counter() + self.cnt = defaultdict(int) def add(self, number: int) -> None: self.cnt[number] += 1 @@ -61,9 +75,8 @@ class TwoSum: def find(self, value: int) -> bool: for x, v in self.cnt.items(): y = value - x - if y in self.cnt: - if x != y or v > 1: - return True + if y in self.cnt and (x != y or v > 1): + return True return False @@ -88,10 +101,8 @@ class TwoSum { for (var e : cnt.entrySet()) { int x = e.getKey(), v = e.getValue(); int y = value - x; - if (cnt.containsKey(y)) { - if (x != y || v > 1) { - return true; - } + if (cnt.containsKey(y) && (x != y || v > 1)) { + return true; } } return false; @@ -119,10 +130,8 @@ public: bool find(int value) { for (auto& [x, v] : cnt) { long y = (long) value - x; - if (cnt.count(y)) { - if (x != y || v > 1) { - return true; - } + if (cnt.contains(y) && (x != y || v > 1)) { + return true; } } return false; @@ -150,7 +159,7 @@ func Constructor() TwoSum { } func (this *TwoSum) Add(number int) { - this.cnt[number]++ + this.cnt[number] += 1 } func (this *TwoSum) Find(value int) bool { @@ -171,6 +180,34 @@ func (this *TwoSum) Find(value int) bool { */ ``` +```ts +class TwoSum { + private cnt: Map = new Map(); + constructor() {} + + add(number: number): void { + this.cnt.set(number, (this.cnt.get(number) || 0) + 1); + } + + find(value: number): boolean { + for (const [x, v] of this.cnt) { + const y = value - x; + if (this.cnt.has(y) && (x !== y || v > 1)) { + return true; + } + } + return false; + } +} + +/** + * Your TwoSum object will be instantiated and called as such: + * var obj = new TwoSum() + * obj.add(number) + * var param_2 = obj.find(value) + */ +``` + diff --git a/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.cpp b/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.cpp index 89185eca55cb3..18636ceeefb2f 100644 --- a/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.cpp +++ b/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.cpp @@ -10,10 +10,8 @@ class TwoSum { bool find(int value) { for (auto& [x, v] : cnt) { long y = (long) value - x; - if (cnt.count(y)) { - if (x != y || v > 1) { - return true; - } + if (cnt.contains(y) && (x != y || v > 1)) { + return true; } } return false; diff --git a/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.go b/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.go index 2408d92446dd7..54a4fe41981aa 100644 --- a/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.go +++ b/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.go @@ -7,7 +7,7 @@ func Constructor() TwoSum { } func (this *TwoSum) Add(number int) { - this.cnt[number]++ + this.cnt[number] += 1 } func (this *TwoSum) Find(value int) bool { diff --git a/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.java b/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.java index 154d2618f1f0f..24382fa333b18 100644 --- a/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.java +++ b/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.java @@ -12,10 +12,8 @@ public boolean find(int value) { for (var e : cnt.entrySet()) { int x = e.getKey(), v = e.getValue(); int y = value - x; - if (cnt.containsKey(y)) { - if (x != y || v > 1) { - return true; - } + if (cnt.containsKey(y) && (x != y || v > 1)) { + return true; } } return false; diff --git a/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.py b/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.py index 49bd6a801e9c6..64044d2d9cffd 100644 --- a/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.py +++ b/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.py @@ -1,6 +1,7 @@ class TwoSum: + def __init__(self): - self.cnt = Counter() + self.cnt = defaultdict(int) def add(self, number: int) -> None: self.cnt[number] += 1 @@ -8,9 +9,8 @@ def add(self, number: int) -> None: def find(self, value: int) -> bool: for x, v in self.cnt.items(): y = value - x - if y in self.cnt: - if x != y or v > 1: - return True + if y in self.cnt and (x != y or v > 1): + return True return False diff --git a/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.ts b/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.ts new file mode 100644 index 0000000000000..9f2e673ee0314 --- /dev/null +++ b/solution/0100-0199/0170.Two Sum III - Data structure design/Solution.ts @@ -0,0 +1,25 @@ +class TwoSum { + private cnt: Map = new Map(); + constructor() {} + + add(number: number): void { + this.cnt.set(number, (this.cnt.get(number) || 0) + 1); + } + + find(value: number): boolean { + for (const [x, v] of this.cnt) { + const y = value - x; + if (this.cnt.has(y) && (x !== y || v > 1)) { + return true; + } + } + return false; + } +} + +/** + * Your TwoSum object will be instantiated and called as such: + * var obj = new TwoSum() + * obj.add(number) + * var param_2 = obj.find(value) + */ diff --git a/solution/0100-0199/0171.Excel Sheet Column Number/README.md b/solution/0100-0199/0171.Excel Sheet Column Number/README.md index 5fea483460f71..bf8334e388bc7 100644 --- a/solution/0100-0199/0171.Excel Sheet Column Number/README.md +++ b/solution/0100-0199/0171.Excel Sheet Column Number/README.md @@ -56,27 +56,33 @@ AB -> 28 ## 解法 -### 方法一 +### 方法一:进制转换 + +Excel 表格中的列名称是一种 26 进制的表示方法。例如,"AB" 表示的列序号是 $1 \times 26 + 2 = 28$。 + +因此,我们可以遍历字符串 `columnTitle`,将每个字符转换为对应的数值,然后计算结果即可。 + +时间复杂度 $O(n)$,其中 $n$ 是字符串 `columnTitle` 的长度。空间复杂度 $O(1)$。 ```python class Solution: def titleToNumber(self, columnTitle: str) -> int: - res = 0 - for c in columnTitle: - res = res * 26 + (ord(c) - ord('A') + 1) - return res + ans = 0 + for c in map(ord, columnTitle): + ans = ans * 26 + c - ord("A") + 1 + return ans ``` ```java class Solution { public int titleToNumber(String columnTitle) { - int res = 0; - for (char c : columnTitle.toCharArray()) { - res = res * 26 + (c - 'A' + 1); + int ans = 0; + for (int i = 0; i < columnTitle.length(); ++i) { + ans = ans * 26 + (columnTitle.charAt(i) - 'A' + 1); } - return res; + return ans; } } ``` @@ -85,32 +91,43 @@ class Solution { class Solution { public: int titleToNumber(string columnTitle) { - int res = 0; - for (char c : columnTitle) { - res = res * 26 + (c - 'A' + 1); + int ans = 0; + for (char& c : columnTitle) { + ans = ans * 26 + (c - 'A' + 1); } - return res; + return ans; } }; ``` ```go -func titleToNumber(columnTitle string) int { - res := 0 +func titleToNumber(columnTitle string) (ans int) { for _, c := range columnTitle { - res = res*26 + int(c-'A'+1) + ans = ans*26 + int(c-'A'+1) } - return res + return } ``` ```ts function titleToNumber(columnTitle: string): number { - let res: number = 0; - for (let char of columnTitle) { - res = res * 26 + char.charCodeAt(0) - 64; + let ans: number = 0; + for (const c of columnTitle) { + ans = ans * 26 + (c.charCodeAt(0) - 'A'.charCodeAt(0) + 1); + } + return ans; +} +``` + +```cs +public class Solution { + public int TitleToNumber(string columnTitle) { + int ans = 0; + foreach (char c in columnTitle) { + ans = ans * 26 + c - 'A' + 1; + } + return ans; } - return res; } ``` diff --git a/solution/0100-0199/0171.Excel Sheet Column Number/README_EN.md b/solution/0100-0199/0171.Excel Sheet Column Number/README_EN.md index 619c26532f79e..3c0437ba24a5f 100644 --- a/solution/0100-0199/0171.Excel Sheet Column Number/README_EN.md +++ b/solution/0100-0199/0171.Excel Sheet Column Number/README_EN.md @@ -54,27 +54,33 @@ AB -> 28 ## Solutions -### Solution 1 +### Solution 1: Base Conversion + +The column name in Excel is a representation in base 26. For example, "AB" represents the column number $1 \times 26 + 2 = 28$. + +Therefore, we can iterate through the string `columnTitle`, convert each character to its corresponding value, and then calculate the result. + +The time complexity is $O(n)$, where $n$ is the length of the string `columnTitle`. The space complexity is $O(1)$. ```python class Solution: def titleToNumber(self, columnTitle: str) -> int: - res = 0 - for c in columnTitle: - res = res * 26 + (ord(c) - ord('A') + 1) - return res + ans = 0 + for c in map(ord, columnTitle): + ans = ans * 26 + c - ord("A") + 1 + return ans ``` ```java class Solution { public int titleToNumber(String columnTitle) { - int res = 0; - for (char c : columnTitle.toCharArray()) { - res = res * 26 + (c - 'A' + 1); + int ans = 0; + for (int i = 0; i < columnTitle.length(); ++i) { + ans = ans * 26 + (columnTitle.charAt(i) - 'A' + 1); } - return res; + return ans; } } ``` @@ -83,32 +89,43 @@ class Solution { class Solution { public: int titleToNumber(string columnTitle) { - int res = 0; - for (char c : columnTitle) { - res = res * 26 + (c - 'A' + 1); + int ans = 0; + for (char& c : columnTitle) { + ans = ans * 26 + (c - 'A' + 1); } - return res; + return ans; } }; ``` ```go -func titleToNumber(columnTitle string) int { - res := 0 +func titleToNumber(columnTitle string) (ans int) { for _, c := range columnTitle { - res = res*26 + int(c-'A'+1) + ans = ans*26 + int(c-'A'+1) } - return res + return } ``` ```ts function titleToNumber(columnTitle: string): number { - let res: number = 0; - for (let char of columnTitle) { - res = res * 26 + char.charCodeAt(0) - 64; + let ans: number = 0; + for (const c of columnTitle) { + ans = ans * 26 + (c.charCodeAt(0) - 'A'.charCodeAt(0) + 1); + } + return ans; +} +``` + +```cs +public class Solution { + public int TitleToNumber(string columnTitle) { + int ans = 0; + foreach (char c in columnTitle) { + ans = ans * 26 + c - 'A' + 1; + } + return ans; } - return res; } ``` diff --git a/solution/0100-0199/0171.Excel Sheet Column Number/Solution.cpp b/solution/0100-0199/0171.Excel Sheet Column Number/Solution.cpp index 5f35b6a95d26c..77faf1be82b31 100644 --- a/solution/0100-0199/0171.Excel Sheet Column Number/Solution.cpp +++ b/solution/0100-0199/0171.Excel Sheet Column Number/Solution.cpp @@ -1,10 +1,10 @@ class Solution { public: int titleToNumber(string columnTitle) { - int res = 0; - for (char c : columnTitle) { - res = res * 26 + (c - 'A' + 1); + int ans = 0; + for (char& c : columnTitle) { + ans = ans * 26 + (c - 'A' + 1); } - return res; + return ans; } }; \ No newline at end of file diff --git a/solution/0100-0199/0171.Excel Sheet Column Number/Solution.cs b/solution/0100-0199/0171.Excel Sheet Column Number/Solution.cs new file mode 100644 index 0000000000000..988830ea24777 --- /dev/null +++ b/solution/0100-0199/0171.Excel Sheet Column Number/Solution.cs @@ -0,0 +1,9 @@ +public class Solution { + public int TitleToNumber(string columnTitle) { + int ans = 0; + foreach (char c in columnTitle) { + ans = ans * 26 + c - 'A' + 1; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/0100-0199/0171.Excel Sheet Column Number/Solution.go b/solution/0100-0199/0171.Excel Sheet Column Number/Solution.go index 046ec231e09cb..e38d327e302da 100644 --- a/solution/0100-0199/0171.Excel Sheet Column Number/Solution.go +++ b/solution/0100-0199/0171.Excel Sheet Column Number/Solution.go @@ -1,7 +1,6 @@ -func titleToNumber(columnTitle string) int { - res := 0 +func titleToNumber(columnTitle string) (ans int) { for _, c := range columnTitle { - res = res*26 + int(c-'A'+1) + ans = ans*26 + int(c-'A'+1) } - return res + return } \ No newline at end of file diff --git a/solution/0100-0199/0171.Excel Sheet Column Number/Solution.java b/solution/0100-0199/0171.Excel Sheet Column Number/Solution.java index 11ba10f8b0d94..4430920130c4e 100644 --- a/solution/0100-0199/0171.Excel Sheet Column Number/Solution.java +++ b/solution/0100-0199/0171.Excel Sheet Column Number/Solution.java @@ -1,9 +1,9 @@ class Solution { public int titleToNumber(String columnTitle) { - int res = 0; - for (char c : columnTitle.toCharArray()) { - res = res * 26 + (c - 'A' + 1); + int ans = 0; + for (int i = 0; i < columnTitle.length(); ++i) { + ans = ans * 26 + (columnTitle.charAt(i) - 'A' + 1); } - return res; + return ans; } } \ No newline at end of file diff --git a/solution/0100-0199/0171.Excel Sheet Column Number/Solution.py b/solution/0100-0199/0171.Excel Sheet Column Number/Solution.py index c5c4729d6e7a7..694dc807d006b 100644 --- a/solution/0100-0199/0171.Excel Sheet Column Number/Solution.py +++ b/solution/0100-0199/0171.Excel Sheet Column Number/Solution.py @@ -1,6 +1,6 @@ class Solution: def titleToNumber(self, columnTitle: str) -> int: - res = 0 - for c in columnTitle: - res = res * 26 + (ord(c) - ord('A') + 1) - return res + ans = 0 + for c in map(ord, columnTitle): + ans = ans * 26 + c - ord("A") + 1 + return ans diff --git a/solution/0100-0199/0171.Excel Sheet Column Number/Solution.ts b/solution/0100-0199/0171.Excel Sheet Column Number/Solution.ts index b921efb8c30c7..182c7cf6d99cb 100644 --- a/solution/0100-0199/0171.Excel Sheet Column Number/Solution.ts +++ b/solution/0100-0199/0171.Excel Sheet Column Number/Solution.ts @@ -1,7 +1,7 @@ function titleToNumber(columnTitle: string): number { - let res: number = 0; - for (let char of columnTitle) { - res = res * 26 + char.charCodeAt(0) - 64; + let ans: number = 0; + for (const c of columnTitle) { + ans = ans * 26 + (c.charCodeAt(0) - 'A'.charCodeAt(0) + 1); } - return res; + return ans; } diff --git a/solution/0100-0199/0172.Factorial Trailing Zeroes/README_EN.md b/solution/0100-0199/0172.Factorial Trailing Zeroes/README_EN.md index 89a1152486f5e..364463e72c613 100644 --- a/solution/0100-0199/0172.Factorial Trailing Zeroes/README_EN.md +++ b/solution/0100-0199/0172.Factorial Trailing Zeroes/README_EN.md @@ -46,7 +46,18 @@ ## Solutions -### Solution 1 +### Solution 1: Mathematics + +The problem is actually asking how many factors of $5$ are there in $[1,n]$. + +Let's take $130$ as an example for analysis: + +1. Divide by $5$ for the first time, get $26$, indicating that there are $26$ numbers containing the factor $5$; +2. Divide by $5$ for the second time, get $5$, indicating that there are $5$ numbers containing the factor $5^2$; +3. Divide by $5$ for the third time, get $1$, indicating that there is $1$ number containing the factor $5^3$; +4. Sum up to get the count of all factors of $5$ in $[1,n]$. + +The time complexity is $O(\log n)$, and the space complexity is $O(1)$. diff --git a/solution/0100-0199/0174.Dungeon Game/README.md b/solution/0100-0199/0174.Dungeon Game/README.md index 1b7a22f202620..7093d1ecee2ae 100644 --- a/solution/0100-0199/0174.Dungeon Game/README.md +++ b/solution/0100-0199/0174.Dungeon Game/README.md @@ -61,7 +61,7 @@ ### 方法一:动态规划 -定义 $dp[i][j]$ 表示从 $(i, j)$ 到终点所需的最小初始值,那么 $dp[i][j]$ 的值可以由 $dp[i+1][j]$ 和 $dp[i][j+1]$ 得到,即: +我们定义 $dp[i][j]$ 表示从 $(i, j)$ 到终点所需的最小初始值,那么 $dp[i][j]$ 的值可以由 $dp[i+1][j]$ 和 $dp[i][j+1]$ 得到,即: $$ dp[i][j] = \max(\min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j], 1) diff --git a/solution/0100-0199/0174.Dungeon Game/README_EN.md b/solution/0100-0199/0174.Dungeon Game/README_EN.md index 537b6b5f189be..f07d453fdc82e 100644 --- a/solution/0100-0199/0174.Dungeon Game/README_EN.md +++ b/solution/0100-0199/0174.Dungeon Game/README_EN.md @@ -46,7 +46,17 @@ ## Solutions -### Solution 1 +### Solution 1: Dynamic Programming + +We define $dp[i][j]$ as the minimum initial value needed from $(i, j)$ to the end point. The value of $dp[i][j]$ can be obtained from $dp[i+1][j]$ and $dp[i][j+1]$, that is: + +$$ +dp[i][j] = \max(\min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j], 1) +$$ + +Initially, $dp[m][n-1]$ and $dp[m-1][n]$ are both $1$, and the values at other positions are maximum. + +The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Where $m$ and $n$ are the number of rows and columns of the dungeon, respectively. diff --git a/solution/0100-0199/0186.Reverse Words in a String II/README.md b/solution/0100-0199/0186.Reverse Words in a String II/README.md index 34aeefd1462c9..cf5a9ccf58d59 100644 --- a/solution/0100-0199/0186.Reverse Words in a String II/README.md +++ b/solution/0100-0199/0186.Reverse Words in a String II/README.md @@ -48,32 +48,30 @@ ## 解法 -### 方法一 +### 方法一:双指针 + +我们可以遍历字符数组 $s$,利用双指针 $i$ 和 $j$ 找到每个单词的起始位置和结束位置,然后反转每个单词,最后再反转整个字符数组。 + +时间复杂度 $O(n)$,其中 $n$ 为字符数组 $s$ 的长度。空间复杂度 $O(1)$。 ```python class Solution: def reverseWords(self, s: List[str]) -> None: - """ - Do not return anything, modify s in-place instead. - """ - - def reverse(s, i, j): + def reverse(i: int, j: int): while i < j: s[i], s[j] = s[j], s[i] - i += 1 - j -= 1 + i, j = i + 1, j - 1 - i, j, n = 0, 0, len(s) - while j < n: - if s[j] == ' ': - reverse(s, i, j - 1) + i, n = 0, len(s) + for j, c in enumerate(s): + if c == " ": + reverse(i, j - 1) i = j + 1 elif j == n - 1: - reverse(s, i, j) - j += 1 - reverse(s, 0, n - 1) + reverse(i, j) + reverse(0, n - 1) ``` ```java @@ -105,46 +103,65 @@ class Solution { class Solution { public: void reverseWords(vector& s) { + auto reverse = [&](int i, int j) { + for (; i < j; ++i, --j) { + swap(s[i], s[j]); + } + }; int n = s.size(); for (int i = 0, j = 0; j < n; ++j) { if (s[j] == ' ') { - reverse(s, i, j - 1); + reverse(i, j - 1); i = j + 1; } else if (j == n - 1) { - reverse(s, i, j); + reverse(i, j); } } - reverse(s, 0, n - 1); - } - - void reverse(vector& s, int i, int j) { - for (; i < j; ++i, --j) { - swap(s[i], s[j]); - } + reverse(0, n - 1); } }; ``` ```go func reverseWords(s []byte) { - n := len(s) - for i, j := 0, 0; j < n; j++ { - if s[j] == ' ' { - reverse(s, i, j-1) + reverse := func(i, j int) { + for ; i < j; i, j = i+1, j-1 { + s[i], s[j] = s[j], s[i] + } + } + i, n := 0, len(s) + for j, c := range s { + if c == ' ' { + reverse(i, j-1) i = j + 1 } else if j == n-1 { - reverse(s, i, j) + reverse(i, j) } } - reverse(s, 0, n-1) + reverse(0, n-1) } +``` -func reverse(s []byte, i, j int) { - for i < j { - s[i], s[j] = s[j], s[i] - i++ - j-- - } +```ts +/** + Do not return anything, modify s in-place instead. + */ +function reverseWords(s: string[]): void { + const n = s.length; + const reverse = (i: number, j: number): void => { + for (; i < j; ++i, --j) { + [s[i], s[j]] = [s[j], s[i]]; + } + }; + for (let i = 0, j = 0; j <= n; ++j) { + if (s[j] === ' ') { + reverse(i, j - 1); + i = j + 1; + } else if (j === n - 1) { + reverse(i, j); + } + } + reverse(0, n - 1); } ``` diff --git a/solution/0100-0199/0186.Reverse Words in a String II/README_EN.md b/solution/0100-0199/0186.Reverse Words in a String II/README_EN.md index abf96c75d09b4..a421d956cb541 100644 --- a/solution/0100-0199/0186.Reverse Words in a String II/README_EN.md +++ b/solution/0100-0199/0186.Reverse Words in a String II/README_EN.md @@ -33,32 +33,30 @@ ## Solutions -### Solution 1 +### Solution 1: Two Pointers + +We can iterate through the character array $s$, using two pointers $i$ and $j$ to find the start and end positions of each word, then reverse each word, and finally reverse the entire character array. + +The time complexity is $O(n)$, where $n$ is the length of the character array $s$. The space complexity is $O(1)$. ```python class Solution: def reverseWords(self, s: List[str]) -> None: - """ - Do not return anything, modify s in-place instead. - """ - - def reverse(s, i, j): + def reverse(i: int, j: int): while i < j: s[i], s[j] = s[j], s[i] - i += 1 - j -= 1 + i, j = i + 1, j - 1 - i, j, n = 0, 0, len(s) - while j < n: - if s[j] == ' ': - reverse(s, i, j - 1) + i, n = 0, len(s) + for j, c in enumerate(s): + if c == " ": + reverse(i, j - 1) i = j + 1 elif j == n - 1: - reverse(s, i, j) - j += 1 - reverse(s, 0, n - 1) + reverse(i, j) + reverse(0, n - 1) ``` ```java @@ -90,46 +88,65 @@ class Solution { class Solution { public: void reverseWords(vector& s) { + auto reverse = [&](int i, int j) { + for (; i < j; ++i, --j) { + swap(s[i], s[j]); + } + }; int n = s.size(); for (int i = 0, j = 0; j < n; ++j) { if (s[j] == ' ') { - reverse(s, i, j - 1); + reverse(i, j - 1); i = j + 1; } else if (j == n - 1) { - reverse(s, i, j); + reverse(i, j); } } - reverse(s, 0, n - 1); - } - - void reverse(vector& s, int i, int j) { - for (; i < j; ++i, --j) { - swap(s[i], s[j]); - } + reverse(0, n - 1); } }; ``` ```go func reverseWords(s []byte) { - n := len(s) - for i, j := 0, 0; j < n; j++ { - if s[j] == ' ' { - reverse(s, i, j-1) + reverse := func(i, j int) { + for ; i < j; i, j = i+1, j-1 { + s[i], s[j] = s[j], s[i] + } + } + i, n := 0, len(s) + for j, c := range s { + if c == ' ' { + reverse(i, j-1) i = j + 1 } else if j == n-1 { - reverse(s, i, j) + reverse(i, j) } } - reverse(s, 0, n-1) + reverse(0, n-1) } +``` -func reverse(s []byte, i, j int) { - for i < j { - s[i], s[j] = s[j], s[i] - i++ - j-- - } +```ts +/** + Do not return anything, modify s in-place instead. + */ +function reverseWords(s: string[]): void { + const n = s.length; + const reverse = (i: number, j: number): void => { + for (; i < j; ++i, --j) { + [s[i], s[j]] = [s[j], s[i]]; + } + }; + for (let i = 0, j = 0; j <= n; ++j) { + if (s[j] === ' ') { + reverse(i, j - 1); + i = j + 1; + } else if (j === n - 1) { + reverse(i, j); + } + } + reverse(0, n - 1); } ``` diff --git a/solution/0100-0199/0186.Reverse Words in a String II/Solution.cpp b/solution/0100-0199/0186.Reverse Words in a String II/Solution.cpp index 453f0d533b604..41092c17e9cea 100644 --- a/solution/0100-0199/0186.Reverse Words in a String II/Solution.cpp +++ b/solution/0100-0199/0186.Reverse Words in a String II/Solution.cpp @@ -1,21 +1,20 @@ class Solution { public: void reverseWords(vector& s) { + auto reverse = [&](int i, int j) { + for (; i < j; ++i, --j) { + swap(s[i], s[j]); + } + }; int n = s.size(); for (int i = 0, j = 0; j < n; ++j) { if (s[j] == ' ') { - reverse(s, i, j - 1); + reverse(i, j - 1); i = j + 1; } else if (j == n - 1) { - reverse(s, i, j); + reverse(i, j); } } - reverse(s, 0, n - 1); - } - - void reverse(vector& s, int i, int j) { - for (; i < j; ++i, --j) { - swap(s[i], s[j]); - } + reverse(0, n - 1); } }; \ No newline at end of file diff --git a/solution/0100-0199/0186.Reverse Words in a String II/Solution.go b/solution/0100-0199/0186.Reverse Words in a String II/Solution.go index 148afd3eb0542..8dd22464f2a95 100644 --- a/solution/0100-0199/0186.Reverse Words in a String II/Solution.go +++ b/solution/0100-0199/0186.Reverse Words in a String II/Solution.go @@ -1,20 +1,17 @@ func reverseWords(s []byte) { - n := len(s) - for i, j := 0, 0; j < n; j++ { - if s[j] == ' ' { - reverse(s, i, j-1) + reverse := func(i, j int) { + for ; i < j; i, j = i+1, j-1 { + s[i], s[j] = s[j], s[i] + } + } + i, n := 0, len(s) + for j, c := range s { + if c == ' ' { + reverse(i, j-1) i = j + 1 } else if j == n-1 { - reverse(s, i, j) + reverse(i, j) } } - reverse(s, 0, n-1) -} - -func reverse(s []byte, i, j int) { - for i < j { - s[i], s[j] = s[j], s[i] - i++ - j-- - } + reverse(0, n-1) } \ No newline at end of file diff --git a/solution/0100-0199/0186.Reverse Words in a String II/Solution.py b/solution/0100-0199/0186.Reverse Words in a String II/Solution.py index acc45671eae1a..d3893a0896195 100644 --- a/solution/0100-0199/0186.Reverse Words in a String II/Solution.py +++ b/solution/0100-0199/0186.Reverse Words in a String II/Solution.py @@ -1,21 +1,15 @@ class Solution: def reverseWords(self, s: List[str]) -> None: - """ - Do not return anything, modify s in-place instead. - """ - - def reverse(s, i, j): + def reverse(i: int, j: int): while i < j: s[i], s[j] = s[j], s[i] - i += 1 - j -= 1 + i, j = i + 1, j - 1 - i, j, n = 0, 0, len(s) - while j < n: - if s[j] == ' ': - reverse(s, i, j - 1) + i, n = 0, len(s) + for j, c in enumerate(s): + if c == " ": + reverse(i, j - 1) i = j + 1 elif j == n - 1: - reverse(s, i, j) - j += 1 - reverse(s, 0, n - 1) + reverse(i, j) + reverse(0, n - 1) diff --git a/solution/0100-0199/0186.Reverse Words in a String II/Solution.ts b/solution/0100-0199/0186.Reverse Words in a String II/Solution.ts new file mode 100644 index 0000000000000..cebd936a0a902 --- /dev/null +++ b/solution/0100-0199/0186.Reverse Words in a String II/Solution.ts @@ -0,0 +1,20 @@ +/** + Do not return anything, modify s in-place instead. + */ +function reverseWords(s: string[]): void { + const n = s.length; + const reverse = (i: number, j: number): void => { + for (; i < j; ++i, --j) { + [s[i], s[j]] = [s[j], s[i]]; + } + }; + for (let i = 0, j = 0; j <= n; ++j) { + if (s[j] === ' ') { + reverse(i, j - 1); + i = j + 1; + } else if (j === n - 1) { + reverse(i, j); + } + } + reverse(0, n - 1); +}