题目描述:
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)
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);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
思路
如果numRows为1,直接返回原字符串。如果是多行,用和行数相同数量的StringBuilder保存对应的每行的结果,再将这些StringBuilder按顺序拼接起来输出。在往StringBuilder中保存字符的过程中,用一个int型变量保存行号,用一个boolean型变量来确认下一次保存字符应该在第几行对应StringBuilder。
代码
public class Solution {
/**
* @param s: the given string
* @param numRows: the number of rows
* @return: the string read line by line
*/
public String convert(String s, int numRows) {
if(numRows<=1||s==null){
return s;
}else{
List<StringBuilder> builderList = new ArrayList<>();
for(int i = 0; i < numRows; i++){
StringBuilder sb = new StringBuilder();
builderList.add(sb);
}
char[] sCharArray = s.toCharArray();
int j = 0;
boolean raise = true;
for (int i = 0; i < sCharArray.length; i++){
char c = sCharArray[i];
builderList.get(j).append(c);
if(raise){
j++;
if(j == numRows - 1){
raise = false;
}
}else{
j--;
if(j == 0){
raise = true;
}
}
}
StringBuilder result = new StringBuilder();
for(StringBuilder sb : builderList){
result.append(sb);
}
return result.toString();
}
}
}