Leetcode 6. Zigzag conversionzigzag conversion
Article directory
6. 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:
Direct jump (sideways)
According to the law, for the first and last lines, we can find that the distance between an element and its next element is 2 * numRow - 2.
For the middle element, we can find that its next element is related to its step length. We can start from the first element A of each column, and the distance to the full column element C is 2 * numRow - 2. An element B must be encountered before reaching the next full column element. That is, the total distance of A - > b - > C is 2 * numRow - 2. At the same time, the distance of A - > B plus the distance of B - > C is equal to the total distance. So the step is step (B - > C) = 2 * NumRows - 2 - step (A - > b).
The above can be easily verified by drawing and subscript. In this way, the time complexity is O(n), and the space complexity is O(n^2)
public String convert(String s, int numRows) { if(numRows == 1){ return s; } StringBuilder res = new StringBuilder(); int len = s.length(); for(int i = 0; i < len; i = i + 2 * numRows - 2){ res.append(s.charAt(i)); } for(int i = 1; i < numRows - 1; i++){ int step = 2*i; int index = i; while(index < len){ res.append(s.charAt(index)); step = 2 * numRows - 2 - step; index += step; } } for(int i = numRows - 1; i < len; i = i + 2 * numRows - 2){ res.append(s.charAt(i)); } return res.toString(); }
Zipper method (vertical walk)
The splicing method is to follow the order of the original string. Similar to zipper method. Set an array whose length is numRows, and each array corresponds to a linked list. Each character of the string is then added to the corresponding position. Output the string as a linked list. In this way, the time complexity is O(n), and the space complexity is O(n^2)
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(); } ringBuilder(); for (StringBuilder row : rows) ret.append(row); return ret.toString(); }