程序媛詹妮弗
终身学习

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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"


Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"

Explanation: P I N A L S I G Y A H R P I

 

Solution1: 

Step1: new StringBuilder[]. For each row, allocate a new StringBuilder to save characters in such row. 

         Pay attention! StringBuilder is treated like variable-length arrays. So StringBuilder[] is like array of array

Step2: we can observe that for 1st and last row,  chars will be added into sb[0] and sb[numRows-1], seperately.

                                       for sloping slide,  chars will be added in sb[numRows -2 ] ... sb[1]

Step3: convert each row's StringBuilder into result String

 

code:

 1 /*
 2 Time Complexity: O(n)
 3 Space Complexity: O(n)
 4 */
 5 
 6 class Solution {
 7    public String convert(String s, int numRows) {
 8         char[] c = s.toCharArray();
 9         int len = c.length;
10         StringBuilder[] sb = new StringBuilder[numRows];
11         // 要按row来进行遍历,每一个row先allocate一个StringBuilder
12         for (int i = 0; i < sb.length; i++) {
13             sb[i] = new StringBuilder();
14         }
15 
16         int idx = 0; //用来扫String s
17         while (idx < len) {
18             for (int i = 0; i < numRows && idx < len; i++) {
19                 sb[i].append(c[idx++]);
20             }
21             // sloping side
22             for (int i = numRows - 2; i >= 1 && idx < len; i--) {
23                 sb[i].append(c[idx++]);
24             }
25 
26         }
27         //从sb[0]开始,将sb[1], sb[2], sb[3]... append到一个StringBuilder
28         for (int i = 1; i < sb.length; i++) {
29             sb[0].append(sb[i]);
30         }
31         return sb[0].toString();
32     }
33 }

 

posted on 2019-04-04 07:24  程序媛詹妮弗  阅读(233)  评论(0编辑  收藏  举报