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 62dfbd3

Browse files
committed
6
1 parent feb2a92 commit 62dfbd3

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

‎6. ZigZag Conversion.java

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/*
2+
题目:
3+
4+
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
5+
6+
P A H N
7+
A P L S I I G
8+
Y I R
9+
And then read line by line: "PAHNAPLSIIGYIR"
10+
Write the code that will take a string and make this conversion given a number of rows:
11+
12+
string convert(string text, int nRows);
13+
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
14+
*/
15+
16+
/*
17+
解析:
18+
这道题我是没有思路的,完全不知道怎么做,想过用数组存储,但是还是不太清楚。
19+
20+
后来看过别人的思路,发现这种题,就相当于找规律,其实和他的那个之字形没多大关系
21+
22+
先看一下:假设行数为4
23+
0 6 12
24+
1 5 7 11 13
25+
2 4 8 10 14
26+
3 9 15
27+
28+
这就是所谓的之字形排布,
29+
假设行数为row(从0开始)那么每行的间隔:
30+
第0行和最后一行:总间隔 = 2row(2*3=6)
31+
其余行:第一个元素与第二个元素的间隔:总间隔-2row 第二个元素与第三个元素:2row 之后依次类推。。。
32+
33+
找出这个规律之后,就不难了。。
34+
需要注意的是,需要用一个flag来记录,其余行中不同间隔的转换,每轮循环别忘了恢复flag的值。
35+
不懂得话,具体看代码:
36+
*/
37+
38+
class Solution {
39+
public String convert(String s, int numRows) {
40+
int flag = 1;
41+
int row = 0; //行数从0开始计数。
42+
int confirm = 2*(numRows-1);
43+
int part = confirm;//设置间隔,初始是2(行数-1)
44+
//新建一个结果字符串
45+
String result = "";
46+
47+
//针对一些特殊的情况
48+
//行数为1
49+
if(numRows==1) {
50+
return s;
51+
}
52+
53+
while(row<numRows) {
54+
//第0行和最后一行,特殊照顾!
55+
if(row==0||row==numRows-1) {
56+
for(int i = row;i<s.length();i+=confirm) {
57+
result += s.charAt(i);
58+
}
59+
row++;
60+
}
61+
//其余行
62+
else {
63+
64+
for(int i = row ;i<s.length();i+=part) {
65+
result +=s.charAt(i);
66+
if(flag==1){
67+
part=confirm-2*row;
68+
flag=0;
69+
}
70+
else {
71+
part=2*row;
72+
flag=1;
73+
}
74+
75+
}
76+
row++;//行数++
77+
flag=1;//每次要恢复flag的值
78+
}
79+
}
80+
return result;
81+
}
82+
}

0 commit comments

Comments
(0)

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