题目描述:
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".
解题思路:
- 这道题主要还是找规律
- 我的第一个想法是把字符串先用二维数组按照之字形把它存储下来,再按照行依次存储
- 然而在实际的操作中,我发现这样行不太通(主要还是自己太菜,没有想出来)
- 言归正传,我们把之字形的数据分成两部分来看,第一部分是不在拐弯中的数据,第二部分是在拐弯中的数据,即图中加粗的数据
- 对于没有加粗的数据,按照行来看,同一行的数据之间的间隔为 2 * nrows - 2
- 对于加粗的数据,它不会出现在第一行和最后一行,且它的规律为 j + 2 * nrows - 2 - 2 * i,其中 i 为行号,j 为它同行前一个元素在源字符串的位置
- 注意这里的二维数组,只是抽象意义上的数组,实际上并没有用二维数组来存储,我们只是假定数据已经存储在二维数组中,基于此,通过 i,j 来查找它在原字符串中的位置
代码如下:
public String convert(String s, int nRows) {
if(nRows < 2) return s;
int size = 2 * nRows - 2;
String res = "";
// 按行来处理
for(int i = 0; i < nRows; i++){
// 按照固定的间隔在每一行内依次存储
for(int j = i; j < s.length(); j += size){
res += s.charAt(j);
// 求出加粗字体在原字符串的位置,并判断它是否满足条件
int temp = j + size - 2 * i;
if(i != 0 && i != nRows - 1 && temp < s.length()) res +=s.charAt(temp);
}
}
return res;
}