Question:
![Uploading Paste_Image_054225.png . . .]
My code:
public class Solution {
public String convert(String s, int numRows) {
if (s == null || numRows == 0)
return null;
if (numRows == 1 || s.length() == 0)
return s;
int len = s.length();
int unit = 2 * numRows - 2;
int numUnit = len / unit;
int left = len % unit;
int height = numRows;
int width;
if (left == 0)
width = (numRows - 1) * numUnit;
else if (left <= numRows)
width = (numRows - 1) * numUnit + 1;
else if (left > numRows)
width = (numRows - 1) * numUnit + 1 + left - numRows;
else
width = (numRows - 1) * numUnit + 1;
char[][] zigzag = new char[height][width];
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++)
zigzag[j][i] = '@';
int countOfStr = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (countOfStr == s.length())
break;
if (i % (numRows - 1) == 0)
zigzag[j][i] = s.charAt(countOfStr++);
else if ((numRows - (i % (numRows - 1)) - 1) == j)
zigzag[j][i] = s.charAt(countOfStr++);
else
continue;
}
}
String result = "";
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (zigzag[i][j] != '@')
result += zigzag[i][j];
}
}
return result;
}
public static void main(String[] args) {
String s = "PAYPALISHIRING";
Solution test = new Solution();
System.out.println(test.convert(s, 5));
}
}
My test result:
Paste_Image.png
这次作业还是比较简单的,最重要的是,弄懂什么是, ZigZag pattern.
其实就是
。 。 。
。 。。 。。
。 。 。。 。
。 。 。
类似于这种。
然后知道了规则之后,就是一些字符操作了。
具体就不分析了。
**
总结: 没什么好总结的。没多大意思。
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public String convert(String s, int numRows) {
if (s == null || s.length() == 0 || numRows > s.length()) {
return s;
}
StringBuilder[] sb = new StringBuilder[numRows];
for (int i = 0; i < sb.length; i++) {
sb[i] = new StringBuilder();
}
int i = 0;
while (i < s.length()) {
for (int j = 0; j < numRows && i < s.length(); j++, i++) {
sb[j].append(s.charAt(i));
}
for (int j = numRows - 2; j >= 1 && i < s.length(); j--, i++) {
sb[j].append(s.charAt(i));
}
}
for (int j = 1; j < numRows; j++) {
sb[0].append(sb[j]);
}
return sb[0].toString();
}
}
reference:
https://discuss.leetcode.com/topic/3162/easy-to-understand-java-solution
https://discuss.leetcode.com/topic/22925/if-you-are-confused-with-zigzag-pattern-come-and-see
简单题目,直接看的答案,自己写估计又会写的很烦。
然后答案写的很简单,用代码来模拟zigzag的过程。
加油加油!赶紧刷题,抓住机会!
Anyway, Good luck, Richardo! -- 09/06