搜索此博客

2012年8月16日星期四

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".


01 public String convert(String s, int nRows) {
02 
03   char[] cstr=s.toCharArray();
04 
05   if(nRows<=1)
06     return s;
07   StringBuffer []sb=new StringBuffer[nRows];
08   for(int i=0;i<nRows;i++)
09   {
10     sb[i]=new StringBuffer();
11   }
12 
13   int len=2*nRows-2;
14   for(int i=0;i<cstr.length;i++)
15   {
16     int k=i%len;
17     if(k<nRows)
18     {
19       sb[k].append(cstr[i]);
20     }
21     else
22     {
23       sb[2*nRows-k-2].append(cstr[i]);
24     }
25   }
26   StringBuffer result=new StringBuffer();
27   for(int i=0;i<nRows;i++)
28   {
29     result.append(sb[i].toString());
30   }
31   return result.toString();
32 }

2 条评论:

  1. Very elegant solution! Thanks!

    回复删除
    回复
    1. I think this is just the very straightforward solution, nothing much with "elegant".

      删除