Description
https://leetcode.com/problems/zigzag-conversion/
Solving Ideas
https://leetcode.com/problems/zigzag-conversion/solution/
遍历字符串,可以轻松确定每个字符所属的ZigZag模式中的哪一行。
- 使用min(numRows, s.length())确定ZigZag模式的行数
- 遍历字符串,将每个字符追加当相应行的末端
- 每个字符所属的行可以由两个变量来确定:curRow (当前行),goingDown (当前移动方向,向上或者向下)
- 根据题意,goingDown (移动方向)只有在顶部行或者底部行才会改变
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
Solution
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;
ArrayList<StringBuilder> sbs = new ArrayList<>(numRows);
for (int i = 0; i < Math.min(numRows, s.length()); i++) {
sbs.add(new StringBuilder());
}
int curRow = 0;
boolean goingDown = false;
for (char ch : s.toCharArray()) {
sbs.get(curRow).append(ch);
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
curRow += goingDown ? 1 : -1;
}
StringBuilder res = new StringBuilder();
for (StringBuilder sb : sbs) res.append(sb);
return res.toString();
}
}
//public class ZigZagConversion {
// public String convert(String s, int numRows) {
// if (numRows == 1) return s;
//
// int unit = 2 * numRows - 2;
// StringBuilder res = new StringBuilder();
//
// for (int i = 0; i < numRows; i++) {
// for (int j = 0; j + i < s.length(); j += unit) {
// res.append(s.charAt(j + i));
// if (i != 0 && i != numRows - 1 && j + unit - i < s.length()) {
// res.append(s.charAt(j + unit - i));
// }
// }
// }
// return res.toString();
// }
//}