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 text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

分析:https://segmentfault.com/a/1190000005751185

打印题,二话不说,画图,标数字,找规律。
这题其实是EPI这本书里7.11题(Write a string sinusoidally),书里的题规定k=3,在leetcode里k作为参数,所以更难了。
leetcode的这个例子的图非常反人类,其实可以把它画得优美一些,像正弦函数的波浪形:

P       A       H       N
A P L S I I G
Y I R

举个别的例子自己画一下:
ZigZag Conversion

 public class Solution {
public String convert(String s, int nRows) { StringBuffer[] sb = new StringBuffer[nRows];
for (int i = ; i < sb.length; i++) {
sb[i] = new StringBuffer();
} int i = ;
while (i < s.length()) {
for (int idx = ; idx < nRows && i < s.length(); idx++) // vertically down
sb[idx].append(s.charAt(i++));
for (int idx = nRows-; idx >= && i < s.length(); idx--) // obliquely up
sb[idx].append(s.charAt(i++));
}
for (int idx = ; idx < sb.length; idx++)
sb[].append(sb[idx]);
return sb[].toString();
}
}
上一篇:AChartEngine方法的使用及事件汇总


下一篇:mat(Eclipse Memory Analyzer tool)之二--heap dump分析