AC,当输入长度为1时需要特殊处理,处理过程比较暴力
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1) return s;
Queue<Character> tmpQueue = new LinkedList();
//定义一个List,里面装着Queue,每个Queue对应一行
List<Queue<Character>> queueList = new LinkedList<Queue<Character>>();
for (int i = 0; i < numRows; i++) {
Queue<Character> queue = new LinkedList();
queueList.add(queue);
}
//设置seq数组[1,2,3,4,3,2],用于选择List中的Queue
int[] seq = new int[numRows*2-2];
for (int i = 0; i < numRows; i++) {
seq[i] = i;
}
for (int i = numRows; i < numRows*2-2; i++) {
seq[i] = seq[i-1]-1;
}
//取出相应Queue,将s.charAt(i)加入其中
for (int i = 0; i < s.length(); i++) {
tmpQueue = queueList.get(seq[i % (numRows*2-2)]);
tmpQueue.add(s.charAt(i));
queueList.set(seq[i % (numRows*2-2)], tmpQueue);
}
int k = 0;
char[] arr = new char[s.length()];
//按顺序打印Queue
for (int i = 0; i < numRows; i++) {
tmpQueue = queueList.get(i);
while(!tmpQueue.isEmpty()){
arr[k] = tmpQueue.remove();
k++;
}
}
return String.valueOf(arr);
}
}
代码优化,来自官方题解:
- 用Queue是没必要的,用StringBuilder就行了
- curRow 很牛逼,解决了选择相应StringBuilder的问题
- 一开始创建StringBuilder时,应考虑数量为 min(numRows, s.length())
- foreach 语句的写法很简洁
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;
}
StringBuilder ret = new StringBuilder();
for (StringBuilder row : rows) ret.append(row);
return ret.toString();
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/zigzag-conversion/solution/z-zi-xing-bian-huan-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。