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 RAnd 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 text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leetcode.string; | |
/** | |
* Solution: Math 题,找index 规律,遍历, 根据nRow和ZigZag长度来给append每个元素, 所有节点访问一遍,Time O(n) Space O(1) | |
* ZigZig size = 2*n-1. 最后一个节点会重复计算,所以我们用2*n - 2. | |
* 满的列 j =i, index 为 j, j+size, j+2size.... | |
* 不满的 j-2*i+size. | |
* | |
* Reference: | |
* http://fisherlei.blogspot.com/2013/01/leetcode-zigzag-conversion.html | |
* http://codeganker.blogspot.com/2014/02/zigzag-conversion-leetcode.html | |
* @author jeffwan | |
* @date Apr 15, 2014 | |
*/ | |
public class ZigZagConversion { | |
public String convert(String s, int nRows) { | |
if (s == null || s.length() == 0 || nRows <= 0) { | |
return ""; | |
} | |
if (nRows == 1) { | |
return s; | |
} | |
StringBuilder result = new StringBuilder(); | |
int size = 2 * nRows - 2; // ZigZag Length (without last duplicate node) | |
for (int i = 0; i < nRows; i++) { | |
for (int j = i; j < s.length(); j += size) { | |
result.append(s.charAt(j)); | |
if (i != 0 && i != nRows - 1 && j + size - 2 * i < s.length()) { | |
result.append(s.charAt(j + size - 2 * i)); | |
} | |
} | |
} | |
return result.toString(); | |
} | |
} |
No comments:
Post a Comment