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

 1 public class Solution {
 2     public String convert(String s, int nRows) {
 3         if(nRows<=1 || s.length()<=0) return s;
 4         StringBuilder sb = new StringBuilder();
 5         for(int i=0;i<nRows;i++){
 6             for(int j=0,index=i;index<s.length();j++,index=(nRows+nRows-2)*j+i){
 7                 sb.append(s.charAt(index));//add red char
 8                 if(i==0 ||i ==nRows-1)// first and last line don't have green char
 9                     continue;
10                 if(index+(nRows-i-1)*2<s.length()){
11                     sb.append(s.charAt(index+(nRows-i-1)*2));
12                 }
13             }
14         }
15         return sb.toString();
16     }
17 }
View Code

 if(index+(nRows-i-1)*2<len)

index<len

posted @ 2014-02-17 01:44  krunning  阅读(337)  评论(0编辑  收藏  举报