[Leetcode] 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".

 

Solution:

http://harrifeng.github.io/algo/leetcode/zigzag-conversion.html

 1 public class Solution {
 2     public String convert(String s, int nRows) {
 3         if(nRows==1)
 4             return s;
 5         int zigSize=2*nRows-2;
 6         StringBuilder[] sb=new StringBuilder[nRows];
 7         for(int i=0;i<nRows;++i){
 8             sb[i]=new StringBuilder();
 9         }
10         for(int i=0;i<s.length();++i){
11             int newi=i%zigSize;
12             if(newi<nRows){
13                 sb[newi].append(s.charAt(i));
14             }else{
15                 sb[zigSize-newi].append(s.charAt(i));
16             }
17         }
18         StringBuilder result=new StringBuilder();
19         for(StringBuilder i:sb){
20             result.append(i);
21         }
22         return result.toString();
23     }
24 }

 

posted @ 2014-11-17 14:16  Phoebe815  阅读(108)  评论(0编辑  收藏  举报