首页 > 其他 > 详细

[Leetcode] ZigZag Conversion

时间:2014-11-17 15:28:03      阅读:224      评论:0      收藏:0      [点我收藏+]

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 }

 

[Leetcode] ZigZag Conversion

原文:http://www.cnblogs.com/Phoebe815/p/4103495.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!