题目:
解题:
重点在于寻找坐标变化的规律,顺序遍历给定数组char s,设立行数currow个数组,根据规律找出该字符应该放在哪个数组c里面,找出该数组的下标。
设立一个标志为godown,当godown=true时,表示数组下标+1,数组向下方向走;当godown=false时,表示数组下标-1,数组向右方向走;
如何确定godown:
- 初始化godown=false;
-
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
-
用3行为例,下标为0和2时,goingDown反转,下标为1时,不变。
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;//一行照抄
List<StringBuilder> rows = new ArrayList<>();
for (int i = 0; i < Math.min(numRows, s.length()); i++)
rows.add(new StringBuilder());
int curRow = 0;
boolean goingDown = false;//初始化
for (char c : s.toCharArray()) {
rows.get(curRow).append(c);
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
curRow += goingDown ? 1 : -1;//根据godown决定数组下标的变化
}
StringBuilder ret = new StringBuilder();
for (StringBuilder row : rows) ret.append(row);
return ret.toString();
}
}