题意:将字符串按照锯齿形排列,然后把从上到下把所有行顺序输出,组成新的字符串。
例子:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
分析:对于每一行先把往下走的那一列的字符加进去,然后有往上走的字符再加进去即可。时间复杂度是O(n),空间复杂度是O(n),代码如下:
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1) return s;
ArrayList<StringBuilder> sbArr = new ArrayList<>();
for(int i = 0; i < Math.min(numRows, s.length()); i++){
StringBuilder sb = new StringBuilder();
sbArr.add(sb);
}
// 用来统计当前是第几行
int rowCount = 0;
// 用来统计是向下查还是向上查
int downCount = 1;
for(int i = 0; i < s.length(); i++){
if(downCount == 1){
sbArr.get(rowCount).append(s.charAt(i));
if(rowCount < numRows - 1){
rowCount++;
}else{
downCount = 1 - downCount;
rowCount--;
}
}else{
sbArr.get(rowCount).append(s.charAt(i));
if(rowCount > 0){
rowCount--;
}else{
downCount = 1 - downCount;
rowCount++;
}
}
}
StringBuilder result = new StringBuilder();
for(StringBuilder cStr : sbArr){
result.append(cStr);
}
return result.toString();
}
}