0%

Leetcode006 ZigZag Conversion

Problem:

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)

P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);
Example 1:

Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:

P I N
A L S I G
Y A H R
P I

Intuition:

这个题目我的思路是这样的。我们只要最后能够返回一个String rows[]的数组,rows[i]表示的就是经过zigzag转换后第i行的字符串问题就能解决了。

那么进一步来说,我们只要按顺序遍历当前字符串,每经过一个字符就算出它经过zigzag转换之后处于新字符串的哪一行就行了。而算行数这个算法本身并不复杂,在纸上一画直接找规律就行。

最后我们根据rows数组重新拼接字符串就能得到答案。

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public static String convert(String s, int numRows) {
String[] rows=new String[numRows];
for(int i=0;i<numRows;i++){
rows[i]="";
}
for(int i=0;i<s.length();i++){
int row=getRow(i,numRows);
//字符转字符串
rows[row]+=String.valueOf(s.charAt(i));
}
StringBuffer sb=new StringBuffer("");
for(int i=0;i<numRows;i++){
sb.append(rows[i]);
}
return sb.toString();
}
public static int getRow(int index,int numRows){
/*
4 0 0,1 1,2 2,3 3,4 2,5 1
*/
if(numRows==1){
return 0;
}
int ans=index%(2*numRows-2);
if(ans<numRows){
return ans;
}else{
return 2*numRows-2-ans;

}
}