Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
241 changes: 29 additions & 212 deletions solution/0000-0099/0006.Zigzag Conversion/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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$ 的长度。

Expand Down Expand Up @@ -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()
}
}
```
Expand Down Expand Up @@ -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 -->
```
Loading
Loading