java6. ZigZag Conversion

Posted carsonwuu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java6. ZigZag Conversion相关的知识,希望对你有一定的参考价值。

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

 

 n=4时的走法是:

 0       6         12

 1   5  7    11 13

 2 4    8 10    14

 3       9         15 

解法:

对于第一行与最后一行,间隔均为2*n-2.

对于中间的斜行,间隔为当前列j+(2n-2)-2i(i是行).

java实现:

 1 public String convert(String s, int nRows) {  
 2         if(s == null || s.length()==0 || nRows <=0)  
 3             return "";  
 4         if(nRows == 1)  
 5             return s;
 6             
 7         StringBuilder res = new StringBuilder();  
 8         int size = 2*nRows-2;  
 9         for(int i=0;i<nRows;i++){  
10             for(int j=i;j<s.length();j+=size){  
11                 res.append(s.charAt(j));  
12                 if(i != 0 && i != nRows - 1){//except the first row and the last row
13                     int temp = j+size-2*i;
14                     if(temp<s.length())
15                         res.append(s.charAt(temp));
16                 }
17             }                  
18         }  
19         return res.toString();  
20     }

 

以上是关于java6. ZigZag Conversion的主要内容,如果未能解决你的问题,请参考以下文章

ZigZag Conversion

#Leetcode# 6. ZigZag Conversion

ZigZag Conversion

leetcode6. ZigZag Conversion

学习(Swift)Leetcode 6. ZigZag Conversion

6. ZigZag Conversion (字符串的连接)