feat: update solutions to lc problem: No.0006 (#4478)

No.0006.Zigzag Conversion
This commit is contained in:
Libin YANG 2025-06-11 14:07:03 +08:00 committed by GitHub
parent a0a5cb775e
commit e26e506bfa
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 84 additions and 586 deletions

View File

@ -78,9 +78,9 @@ P I
### 方法一:模拟
我们用一个二维数组 $g$ 来模拟 $Z$ 字形排列的过程,其中 $g[i][j]$ 表示第 $i$ 行第 $j$ 列的字符。初始时 $i=0$,另外我们定义一个方向变量 $k$,初始时 $k=-1$,表示向上走。
我们用一个二维数组 $g$ 来模拟 Z 字形排列的过程,其中 $g[i][j]$ 表示第 $i$ 行第 $j$ 列的字符。初始时 $i = 0$,另外我们定义一个方向变量 $k$,初始时 $k = -1$,表示向上走。
我们从左到右遍历字符串 $s$,每次遍历到一个字符 $c$,将其追加到 $g[i]$ 中,如果此时 $i=0$ 或者 $i=numRows-1$,说明当前字符位于 $Z$ 字形排列的拐点,我们将 $k$ 的值反转,即 $k=-k$。接下来,我们将 $i$ 的值更新为 $i+k$,即向上或向下移动一行。继续遍历下一个字符,直到遍历完字符串 $s$,我们返回 $g$ 中所有行拼接后的字符串即可。
我们从左到右遍历字符串 $s$,每次遍历到一个字符 $c$,将其追加到 $g[i]$ 中。如果此时 $i = 0$ 或者 $i = \textit{numRows} - 1$,说明当前字符位于 Z 字形排列的拐点,我们将 $k$ 的值反转,即 $k = -k$。接下来,我们将 $i$ 的值更新为 $i + k$,即向上或向下移动一行。继续遍历下一个字符,直到遍历完字符串 $s$,我们返回 $g$ 中所有行拼接后的字符串即可。
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。
@ -199,29 +199,24 @@ function convert(s: string, numRows: number): string {
```rust
impl Solution {
pub fn convert(s: String, num_rows: i32) -> String {
let num_rows = num_rows as usize;
if num_rows == 1 {
return s;
}
let mut ss = vec![String::new(); num_rows];
let num_rows = num_rows as usize;
let mut g = vec![String::new(); num_rows];
let mut i = 0;
let mut to_down = true;
let mut k = -1;
for c in s.chars() {
ss[i].push(c);
if to_down {
i += 1;
} else {
i -= 1;
}
g[i].push(c);
if i == 0 || i == num_rows - 1 {
to_down = !to_down;
k = -k;
}
i = (i as isize + k) as usize;
}
let mut res = String::new();
for i in 0..num_rows {
res += &ss[i];
}
res
g.concat()
}
}
```
@ -323,220 +318,42 @@ char* convert(char* s, int numRows) {
}
```
<!-- tabs:end -->
<!-- solution:end -->
<!-- solution:start -->
### 方法二
<!-- tabs:start -->
#### Python3
```python
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
group = 2 * numRows - 2
ans = []
for i in range(1, numRows + 1):
interval = group if i == numRows else 2 * numRows - 2 * i
idx = i - 1
while idx < len(s):
ans.append(s[idx])
idx += interval
interval = group - interval
if interval == 0:
interval = group
return ''.join(ans)
```
#### Java
```java
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
StringBuilder ans = new StringBuilder();
int group = 2 * numRows - 2;
for (int i = 1; i <= numRows; i++) {
int interval = i == numRows ? group : 2 * numRows - 2 * i;
int idx = i - 1;
while (idx < s.length()) {
ans.append(s.charAt(idx));
idx += interval;
interval = group - interval;
if (interval == 0) {
interval = group;
}
}
}
return ans.toString();
}
}
```
#### C++
```cpp
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
string ans;
int group = 2 * numRows - 2;
for (int i = 1; i <= numRows; ++i) {
int interval = i == numRows ? group : 2 * numRows - 2 * i;
int idx = i - 1;
while (idx < s.length()) {
ans.push_back(s[idx]);
idx += interval;
interval = group - interval;
if (interval == 0) interval = group;
}
}
return ans;
}
};
```
#### Go
```go
func convert(s string, numRows int) string {
if numRows == 1 {
return s
}
n := len(s)
ans := make([]byte, n)
step := 2*numRows - 2
count := 0
for i := 0; i < numRows; i++ {
for j := 0; j+i < n; j += step {
ans[count] = s[i+j]
count++
if i != 0 && i != numRows-1 && j+step-i < n {
ans[count] = s[j+step-i]
count++
}
}
}
return string(ans)
}
```
#### TypeScript
```ts
function convert(s: string, numRows: number): string {
if (numRows === 1) {
return s;
}
const ss = new Array(numRows).fill('');
let i = 0;
let toDown = true;
for (const c of s) {
ss[i] += c;
if (toDown) {
i++;
} else {
i--;
}
if (i === 0 || i === numRows - 1) {
toDown = !toDown;
}
}
return ss.reduce((r, s) => r + s);
}
```
#### Rust
```rust
impl Solution {
pub fn convert(s: String, num_rows: i32) -> String {
let num_rows = num_rows as usize;
let mut rows = vec![String::new(); num_rows];
let iter = (0..num_rows).chain((1..num_rows - 1).rev()).cycle();
iter.zip(s.chars()).for_each(|(i, c)| rows[i].push(c));
rows.into_iter().collect()
}
}
```
#### JavaScript
```js
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function (s, numRows) {
if (numRows == 1) return s;
const arr = new Array(numRows);
for (let i = 0; i < numRows; i++) arr[i] = [];
let mi = 0,
isDown = true;
for (const c of s) {
arr[mi].push(c);
if (mi >= numRows - 1) isDown = false;
else if (mi <= 0) isDown = true;
if (isDown) mi++;
else mi--;
}
let ans = [];
for (const item of arr) {
ans = ans.concat(item);
}
return ans.join('');
};
```
#### PHP
```php
class Solution {
/**
* @param string $s
* @param int $numRows
* @return string
* @param String $s
* @param Integer $numRows
* @return String
*/
function convert($s, $numRows) {
if ($numRows == 1 || strlen($s) <= $numRows) {
if ($numRows == 1) {
return $s;
}
$result = '';
$cycleLength = 2 * $numRows - 2;
$n = strlen($s);
$g = array_fill(0, $numRows, '');
$i = 0;
$k = -1;
for ($i = 0; $i < $numRows; $i++) {
for ($j = 0; $j + $i < $n; $j += $cycleLength) {
$result .= $s[$j + $i];
$length = strlen($s);
for ($j = 0; $j < $length; $j++) {
$c = $s[$j];
$g[$i] .= $c;
if ($i != 0 && $i != $numRows - 1 && $j + $cycleLength - $i < $n) {
$result .= $s[$j + $cycleLength - $i];
}
if ($i == 0 || $i == $numRows - 1) {
$k = -$k;
}
}
return $result;
$i += $k;
}
return implode('', $g);
}
}
``
```
<!-- tabs:end -->
<!-- solution:end -->
<!-- problem:end -->
```

View File

@ -76,11 +76,11 @@ P I
### Solution 1: Simulation
We use a two-dimensional array $g$ to simulate the process of the $Z$-shape arrangement, where $g[i][j]$ represents the character at the $i$-th row and the $j$-th column. Initially, $i=0$, and we define a direction variable $k$, initially $k=-1$, indicating moving upwards.
We use a 2D array $g$ to simulate the process of arranging the string in a zigzag pattern, where $g[i][j]$ represents the character at row $i$ and column $j$. Initially, $i = 0$. We also define a direction variable $k$, initially $k = -1$, which means moving upwards.
We traverse the string $s$ from left to right. Each time we traverse to a character $c$, we append it to $g[i]$. If $i=0$ or $i=numRows-1$ at this time, it means that the current character is at the turning point of the $Z$-shape arrangement, and we reverse the value of $k$, i.e., $k=-k$. Next, we update the value of $i$ to $i+k$, i.e., move up or down one row. Continue to traverse the next character until we have traversed the string $s$, and we return the string concatenated by all rows in $g$.
We traverse the string $s$ from left to right. For each character $c$, we append it to $g[i]$. If $i = 0$ or $i = \textit{numRows} - 1$, it means the current character is at a turning point in the zigzag pattern, so we reverse the value of $k$, i.e., $k = -k$. Then, we update $i$ to $i + k$, which means moving up or down one row. Continue traversing the next character until the end of the string $s$. Finally, we return the concatenation of all rows in $g$ as the result.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$.
The time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the string $s$.
<!-- tabs:start -->
@ -197,29 +197,24 @@ function convert(s: string, numRows: number): string {
```rust
impl Solution {
pub fn convert(s: String, num_rows: i32) -> String {
let num_rows = num_rows as usize;
if num_rows == 1 {
return s;
}
let mut ss = vec![String::new(); num_rows];
let num_rows = num_rows as usize;
let mut g = vec![String::new(); num_rows];
let mut i = 0;
let mut to_down = true;
let mut k = -1;
for c in s.chars() {
ss[i].push(c);
if to_down {
i += 1;
} else {
i -= 1;
}
g[i].push(c);
if i == 0 || i == num_rows - 1 {
to_down = !to_down;
k = -k;
}
i = (i as isize + k) as usize;
}
let mut res = String::new();
for i in 0..num_rows {
res += &ss[i];
}
res
g.concat()
}
}
```
@ -321,213 +316,36 @@ char* convert(char* s, int numRows) {
}
```
<!-- tabs:end -->
<!-- solution:end -->
<!-- solution:start -->
### Solution 2
<!-- tabs:start -->
#### Python3
```python
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
group = 2 * numRows - 2
ans = []
for i in range(1, numRows + 1):
interval = group if i == numRows else 2 * numRows - 2 * i
idx = i - 1
while idx < len(s):
ans.append(s[idx])
idx += interval
interval = group - interval
if interval == 0:
interval = group
return ''.join(ans)
```
#### Java
```java
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
StringBuilder ans = new StringBuilder();
int group = 2 * numRows - 2;
for (int i = 1; i <= numRows; i++) {
int interval = i == numRows ? group : 2 * numRows - 2 * i;
int idx = i - 1;
while (idx < s.length()) {
ans.append(s.charAt(idx));
idx += interval;
interval = group - interval;
if (interval == 0) {
interval = group;
}
}
}
return ans.toString();
}
}
```
#### C++
```cpp
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
string ans;
int group = 2 * numRows - 2;
for (int i = 1; i <= numRows; ++i) {
int interval = i == numRows ? group : 2 * numRows - 2 * i;
int idx = i - 1;
while (idx < s.length()) {
ans.push_back(s[idx]);
idx += interval;
interval = group - interval;
if (interval == 0) interval = group;
}
}
return ans;
}
};
```
#### Go
```go
func convert(s string, numRows int) string {
if numRows == 1 {
return s
}
n := len(s)
ans := make([]byte, n)
step := 2*numRows - 2
count := 0
for i := 0; i < numRows; i++ {
for j := 0; j+i < n; j += step {
ans[count] = s[i+j]
count++
if i != 0 && i != numRows-1 && j+step-i < n {
ans[count] = s[j+step-i]
count++
}
}
}
return string(ans)
}
```
#### TypeScript
```ts
function convert(s: string, numRows: number): string {
if (numRows === 1) {
return s;
}
const ss = new Array(numRows).fill('');
let i = 0;
let toDown = true;
for (const c of s) {
ss[i] += c;
if (toDown) {
i++;
} else {
i--;
}
if (i === 0 || i === numRows - 1) {
toDown = !toDown;
}
}
return ss.reduce((r, s) => r + s);
}
```
#### Rust
```rust
impl Solution {
pub fn convert(s: String, num_rows: i32) -> String {
let num_rows = num_rows as usize;
let mut rows = vec![String::new(); num_rows];
let iter = (0..num_rows).chain((1..num_rows - 1).rev()).cycle();
iter.zip(s.chars()).for_each(|(i, c)| rows[i].push(c));
rows.into_iter().collect()
}
}
```
#### JavaScript
```js
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function (s, numRows) {
if (numRows == 1) return s;
const arr = new Array(numRows);
for (let i = 0; i < numRows; i++) arr[i] = [];
let mi = 0,
isDown = true;
for (const c of s) {
arr[mi].push(c);
if (mi >= numRows - 1) isDown = false;
else if (mi <= 0) isDown = true;
if (isDown) mi++;
else mi--;
}
let ans = [];
for (const item of arr) {
ans = ans.concat(item);
}
return ans.join('');
};
```
#### PHP
```php
class Solution {
/**
* @param string $s
* @param int $numRows
* @return string
* @param String $s
* @param Integer $numRows
* @return String
*/
function convert($s, $numRows) {
if ($numRows == 1 || strlen($s) <= $numRows) {
if ($numRows == 1) {
return $s;
}
$result = '';
$cycleLength = 2 * $numRows - 2;
$n = strlen($s);
$g = array_fill(0, $numRows, '');
$i = 0;
$k = -1;
for ($i = 0; $i < $numRows; $i++) {
for ($j = 0; $j + $i < $n; $j += $cycleLength) {
$result .= $s[$j + $i];
$length = strlen($s);
for ($j = 0; $j < $length; $j++) {
$c = $s[$j];
$g[$i] .= $c;
if ($i != 0 && $i != $numRows - 1 && $j + $cycleLength - $i < $n) {
$result .= $s[$j + $cycleLength - $i];
}
if ($i == 0 || $i == $numRows - 1) {
$k = -$k;
}
}
return $result;
$i += $k;
}
return implode('', $g);
}
}
```

View File

@ -1,29 +1,29 @@
class Solution {
/**
* @param string $s
* @param int $numRows
* @return string
* @param String $s
* @param Integer $numRows
* @return String
*/
function convert($s, $numRows) {
if ($numRows == 1 || strlen($s) <= $numRows) {
if ($numRows == 1) {
return $s;
}
$result = '';
$cycleLength = 2 * $numRows - 2;
$n = strlen($s);
$g = array_fill(0, $numRows, "");
$i = 0;
$k = -1;
for ($i = 0; $i < $numRows; $i++) {
for ($j = 0; $j + $i < $n; $j += $cycleLength) {
$result .= $s[$j + $i];
$length = strlen($s);
for ($j = 0; $j < $length; $j++) {
$c = $s[$j];
$g[$i] .= $c;
if ($i != 0 && $i != $numRows - 1 && $j + $cycleLength - $i < $n) {
$result .= $s[$j + $cycleLength - $i];
}
if ($i == 0 || $i == $numRows - 1) {
$k = -$k;
}
}
return $result;
$i += $k;
}
return implode("", $g);
}
}

View File

@ -1,27 +1,22 @@
impl Solution {
pub fn convert(s: String, num_rows: i32) -> String {
let num_rows = num_rows as usize;
if num_rows == 1 {
return s;
}
let mut ss = vec![String::new(); num_rows];
let num_rows = num_rows as usize;
let mut g = vec![String::new(); num_rows];
let mut i = 0;
let mut to_down = true;
let mut k = -1;
for c in s.chars() {
ss[i].push(c);
if to_down {
i += 1;
} else {
i -= 1;
}
g[i].push(c);
if i == 0 || i == num_rows - 1 {
to_down = !to_down;
k = -k;
}
i = (i as isize + k) as usize;
}
let mut res = String::new();
for i in 0..num_rows {
res += &ss[i];
}
res
g.concat()
}
}

View File

@ -1,19 +0,0 @@
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
string ans;
int group = 2 * numRows - 2;
for (int i = 1; i <= numRows; ++i) {
int interval = i == numRows ? group : 2 * numRows - 2 * i;
int idx = i - 1;
while (idx < s.length()) {
ans.push_back(s[idx]);
idx += interval;
interval = group - interval;
if (interval == 0) interval = group;
}
}
return ans;
}
};

View File

@ -1,20 +0,0 @@
func convert(s string, numRows int) string {
if numRows == 1 {
return s
}
n := len(s)
ans := make([]byte, n)
step := 2*numRows - 2
count := 0
for i := 0; i < numRows; i++ {
for j := 0; j+i < n; j += step {
ans[count] = s[i+j]
count++
if i != 0 && i != numRows-1 && j+step-i < n {
ans[count] = s[j+step-i]
count++
}
}
}
return string(ans)
}

View File

@ -1,22 +0,0 @@
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
StringBuilder ans = new StringBuilder();
int group = 2 * numRows - 2;
for (int i = 1; i <= numRows; i++) {
int interval = i == numRows ? group : 2 * numRows - 2 * i;
int idx = i - 1;
while (idx < s.length()) {
ans.append(s.charAt(idx));
idx += interval;
interval = group - interval;
if (interval == 0) {
interval = group;
}
}
}
return ans.toString();
}
}

View File

@ -1,26 +0,0 @@
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function (s, numRows) {
if (numRows == 1) return s;
const arr = new Array(numRows);
for (let i = 0; i < numRows; i++) arr[i] = [];
let mi = 0,
isDown = true;
for (const c of s) {
arr[mi].push(c);
if (mi >= numRows - 1) isDown = false;
else if (mi <= 0) isDown = true;
if (isDown) mi++;
else mi--;
}
let ans = [];
for (const item of arr) {
ans = ans.concat(item);
}
return ans.join('');
};

View File

@ -1,16 +0,0 @@
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
group = 2 * numRows - 2
ans = []
for i in range(1, numRows + 1):
interval = group if i == numRows else 2 * numRows - 2 * i
idx = i - 1
while idx < len(s):
ans.append(s[idx])
idx += interval
interval = group - interval
if interval == 0:
interval = group
return ''.join(ans)

View File

@ -1,9 +0,0 @@
impl Solution {
pub fn convert(s: String, num_rows: i32) -> String {
let num_rows = num_rows as usize;
let mut rows = vec![String::new(); num_rows];
let iter = (0..num_rows).chain((1..num_rows - 1).rev()).cycle();
iter.zip(s.chars()).for_each(|(i, c)| rows[i].push(c));
rows.into_iter().collect()
}
}

View File

@ -1,20 +0,0 @@
function convert(s: string, numRows: number): string {
if (numRows === 1) {
return s;
}
const ss = new Array(numRows).fill('');
let i = 0;
let toDown = true;
for (const c of s) {
ss[i] += c;
if (toDown) {
i++;
} else {
i--;
}
if (i === 0 || i === numRows - 1) {
toDown = !toDown;
}
}
return ss.reduce((r, s) => r + s);
}