leetcode: 6. ZigZag Conversion
阿新 • • 發佈:2018-12-28
Difficulty
Medium
Description
/**
* The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
* P A H N
* A P L S I I G
* Y I R
* And then read line by line: "PAHNAPLSIIGYIR"
*
* Example 1:
* Input: s = "PAYPALISHIRING", numRows = 3
* Output: "PAHNAPLSIIGYIR"
*/
Solution
Time Complexity: O(n), where n == len(s)
Space Complexity: O(n)
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;
List<StringBuilder> rows = new ArrayList<>();
//Math.min(numRows, s.length())為非空行數
for (int i = 0; i < Math.min(numRows, s.length()); i++) {
rows.add(new StringBuilder());
}
int curRow = 0; //當前所在行
boolean goDown = false; //當前字母走向
for (char c: s.toCharArray()) {
rows.get(curRow).append(c);
if (curRow == 0 || curRow + 1 == numRows) //第一行和最後一行時改變走向
goDown = !goDown;
curRow += goDown? 1 : -1;
}
StringBuilder ret = new StringBuilder();
for (StringBuilder row: rows)
ret.append(row);
return ret.toString();
}
}