首页 > 代码库 > LeetCode 6 ZigZag Conversion

LeetCode 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   NA P L S I I GY   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".

 

思路:

可以设立与行数相同的String数组,然后通过一个循环变量遍历整个字符串的时候将对应的字符加入到对应的字符串中。单次循环内主要有两个步骤:一为向下的遍历,从0到nRows - 1;二为向斜上的遍历,从nRows - 2到1.这样就可以成功遍历整个字符串。另外,考虑到较多的字符串拼接,可以用StringBuffer类或者StringBuilder类代替String类,减小开销。

 

解法:

 1 public class Solution 2 { 3     public String convert(String s, int numRows) 4     { 5         if(numRows == 1) 6             return s; 7  8         StringBuffer[] strbuf = new StringBuffer[numRows]; 9         for(int i = 0; i < numRows; i++)10             strbuf[i] = new StringBuffer();11 12         char[] sArray = s.toCharArray();13         int i = 0;14 15         while(i < sArray.length)16         {17             for(int j = 0; j < numRows && i < sArray.length; j++)18                 strbuf[j].append(sArray[i++]);19             for(int j = numRows - 2; j >0 && i < sArray.length; j++)20                 strbuf[j].append(sArray[i++]);21         }22 23         for(int i = 1; i < numRows; i++)24             strbuf[0].append(strbuf[i]);25 26         return strbuf[0].toString();27     }28 }

 

LeetCode 6 ZigZag Conversion