题目:
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 text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
解决方案:首先关于ZigZag ,将题中所给出的例子写成如下形式会帮助理解什么是ZigZag:
P A H N
A P L S I I G
Y I R
关键在于判断字符串中每一个字符属于哪一行,将题目中的例子数字化如下:
0 4 8 12
1 3 5 7 9 11 13
2 6 10
易看出,可以以4为周期将该字符串进行划分,观察每一行
第一行:0%4 = 4%4 = 8%4 = 12%4 = 0
第二行:1%4 = 5%4 = 9%4 = 13%4 = 1,3%4 = 7%4 = 11%4 = 3,3+1 = 4
第三行:2%4 = 6%4 = 10%4 =2
那么我们可以发现以下规律:对于第i行,i从0开始,其所包含的元素在字符串中的位置n(从0开始)满足以下规律:n%(划分周期)=i或者,n%(划分周期)+i =周期。于是,可以写出如下程序:
-
public class Solution {
-
public String convert(String s, int nRows) {
-
if(nRows == 1){
-
return s;
-
}
-
else{
-
char[] myarr = s.toCharArray();
-
int len = myarr.length;
-
String[] mystrarr = new String[nRows];
-
for(int m = 0; m < nRows; m++){
-
mystrarr[m] = new String();
-
}
-
String result = new String();
-
int periodlen = 2*(nRows-1);
-
for(int i = 0; i < len; i++){
-
int diff = i%periodlen;
-
for(int j = 0; j < nRows; j++){
-
if(diff == j || diff +j == periodlen){
-
mystrarr[j] += myarr[i];
-
}
-
}
-
}
-
for(int n = 0; n < nRows; n++){
-
result += mystrarr[n];
-
}
-
return result;
-
}
-
-
}
-
}
阅读(853) | 评论(0) | 转发(0) |