ZigZag Conversion
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)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P I N
A L S I G
Y A H R
P I
题目分析
给定一个字符串,按照给定的行数,纵向呈Z型排列,然后横向打印输出。
看到这个题目,我想到的办法是用一个二维数组存储,然后按行遍历输出,这样的时间复杂度是O(n2)。实现倒是没有很难的地方。
下面直接介绍我看到的题解吧。
采用StringBuilder和链表存储。每个节点存储行,然后每一个节点存储StringBuilder型的字符串。
其实不难看出,这个Z型字符串是一个蛇形的排列。我们设定边界是0和行数,然后依次在一个节点中存储char。(垂直也好,倾斜也好,从上到下长度都是numRows)
代码
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;//若长度为1,和行数没有关系
List<StringBuilder> rows = new ArrayList<>();
for (int i = 0; i < Math.min(numRows, s.length()); i++)
rows.add(new StringBuilder());//一行为一个节点,若是nums比较大,则一列就好了
int curRow = 0;
boolean goingDown = false;//是否转向
for (char c : s.toCharArray()) {
rows.get(curRow).append(c);//判断行数,在对应节点字符串添加char
if (curRow == 0 || curRow == numRows - 1)
goingDown = !goingDown;//若是达到边界值,既0或者numRows-1
curRow += goingDown ? 1 : -1;//向下遍历增加1,向上遍历则减一,这个简化有点秒
}
//循环添加到一个字符串并返回
StringBuilder ret = new StringBuilder();
for (StringBuilder row : rows)
ret.append(row);
return ret.toString();
}
}