ZigZag Conversion

https://leetcode.com/problems/zigzag-conversion/

题目理解:http://blog.csdn.net/ljiabin/article/details/40477429

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 static String convert(String s, int numRows) {
 3     if(numRows==1) return s;
 4         String[]re=new String[numRows];
 5         for(int i=0;i<numRows;i++){re[i]="";}
 6         int len=s.length();
 7         for(int i=0;i<len;i++){
 8             char c=s.charAt(i);
 9             int row=i%(2*numRows-2);
10             if(row>=numRows) row=2*numRows-row-2;
11             re[row]+=c;
12         }
13         String answer="";
14         for(int i=0;i<numRows;i++){
15             answer+=re[i];
16         }
17         return answer;
18     }
19     public static void main(String[]args){
20     System.out.println(convert("PAYPALISHIRING", 3));
21     }
22 }

 

posted @ 2015-05-04 14:27  打小孩  阅读(123)  评论(0编辑  收藏  举报