zoukankan      html  css  js  c++  java
  • [leetcode]6. ZigZag Conversion字符串Z形排列

    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 }
  • 相关阅读:
    (转)构建自己的AngularJS,第一部分:Scope和Digest
    使用CSS3 制作一个material-design 风格登录界面
    SS
    从零开始构建 Wijmo & Angular 2 小应用
    JavaScript使用构造函数获取变量的类型名
    Luogu-1527 [国家集训队]矩阵乘法
    Codeforces Round #525 (Div. 2)
    BZOJ-3879: SvT
    BZOJ-1396: 识别子串
    计算几何模板
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10652751.html
Copyright © 2011-2022 走看看