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

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


 1 public class Solution {
 2     public String convert(String s, int nRows) {
 3         
 4         StringBuffer[] sb = new StringBuffer[nRows];
 5         for (int i = 0; i < sb.length; i++) {
 6             sb[i] = new StringBuffer();
 7         }
 8         
 9         int i = 0;
10         while (i < s.length()) {
11             for (int idx = 0; idx < nRows && i < s.length(); idx++) // vertically down
12                 sb[idx].append(s.charAt(i++));
13             for (int idx = nRows-2; idx >= 1 && i < s.length(); idx--) // obliquely up
14                 sb[idx].append(s.charAt(i++));
15         }
16         for (int idx = 1; idx < sb.length; idx++)
17             sb[0].append(sb[idx]);
18         return sb[0].toString();
19     }
20 }

 

posted @ 2016-08-05 11:49  北叶青藤  阅读(239)  评论(0)    收藏  举报