Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 05e7d0a

Browse files
committed
docs: add README for solution 0006
1 parent 0202587 commit 05e7d0a

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
## Z 字形变换
2+
### 题目描述
3+
4+
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
5+
6+
比如输入字符串为 `"LEETCODEISHIRING"` 行数为 3 时,排列如下:
7+
8+
```
9+
L C I R
10+
E T O E S I I G
11+
E D H N
12+
```
13+
14+
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:`"LCIRETOESIIGEDHN"`
15+
16+
请你实现这个将字符串进行指定行数变换的函数:
17+
```
18+
string convert(string s, int numRows);
19+
```
20+
21+
**示例 1:**
22+
```
23+
输入: s = "LEETCODEISHIRING", numRows = 3
24+
输出: "LCIRETOESIIGEDHN"
25+
```
26+
27+
**示例 2:**
28+
```
29+
输入: s = "LEETCODEISHIRING", numRows = 4
30+
输出: "LDREOEIIECIHNTSG"
31+
解释:
32+
33+
L D R
34+
E O E I I
35+
E C I H N
36+
T S G
37+
```
38+
39+
### 解法
40+
41+
```java
42+
class Solution {
43+
public String convert(String s, int numRows) {
44+
if (numRows == 1) return s;
45+
StringBuilder result = new StringBuilder();
46+
int group = 2 * numRows - 2;
47+
for (int i = 1; i <= numRows; i++) {
48+
int interval = 2 * numRows - 2 * i;
49+
if (i == numRows) interval = 2 * numRows - 2;
50+
int index = i;
51+
while (index <= s.length()) {
52+
result.append(s.charAt(index - 1));
53+
index += interval;
54+
interval = group - interval;
55+
if (interval == 0) interval = group;
56+
}
57+
}
58+
return result.toString();
59+
}
60+
}
61+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /