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".
大意就是把给定的字符串倒N字形打印,(原意是锯齿状,怎么也联想不出来是倒N字,纠结了好久)
public String convert(String s, int numRows) {
char[] charArray = s.toCharArray();
StringBuilder[] sbArray = new StringBuilder[numRows];
/**
* 由给定例子可以知道,numRows代表了行数,我们实例化numRows个stringbuilder用来存储每一行的字符
* 这样最终结果只要将stringbuilder拼接就可以得到
*/
for(int i = 0;i < numRows; i++){
sbArray[i] = new StringBuilder("");
}
int i = 0 ;
while(i < charArray.length){
/**
* 打印倒N字形的垂直自上向下部分
* 依次填充至sbarray中
*/
for(int idx = 0; i < charArray.length && idx < numRows; idx ++){
sbArray[idx].append(charArray[i++]);
}
/**
* 打印倒N字形自底向斜上部分
* 依次填充至sbarray中,除首尾行之外
*/
for(int idx = numRows - 2; i < charArray.length && idx > 0; idx --){
sbArray[idx].append(charArray[i++]);
}
}
/**
* 拼接得到答案
*/
for(int idx = 1;idx < numRows; idx++){
sbArray[0].append(sbArray[idx]);
}
return sbArray[0].toString();
}
网友评论