The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
1 2 3
P A H N A P L S I I G Y I R
And then read line by line: “PAHNAPLSIIGYIR”
Example1
1 2
Input: s = "PAYPALISHIRING", numRows = 3 Output:"PAHNAPLSIIGYIR"
Example2
1 2 3 4 5 6 7
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: PI N AL S I G YA H R PI
Example3
1 2
Input: s = "A", numRows = 1 Output:"A"
题目大意
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
public String convert(String s, int numRows){ if (numRows < 2) return s; List<StringBuilder> rows = new ArrayList<StringBuilder>(); for (int i = 0; i < numRows; i++) { rows.add(new StringBuilder()); } int i = 0, flag = -1; for (char c : s.toCharArray()) { rows.get(i).append(c); if (i==0 || i==numRows - 1) flag = -flag; i += flag; } StringBuilder res = new StringBuilder(); for (StringBuilder row : rows) { res.append(row); } return res.toString(); }
}
复杂度分析
* 时间复杂度:O(N),遍历一遍字符串 s ; * 空间复杂度:O(N),各行字符串共占用O(N)额外空间。