• LeetCode


    LeetCode - ZigZag Conversion

    2013.12.1 21:48

    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:

    1 string convert(string text, int nRows);

    convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

    Solution:

      This kind of problem is not complicated, and can be done with some calculation on the scratch before you start coding. Still, special cases need special handlings:

        1. the string is empty

        2. nRows = 1

      Time complexity is O(n), where n is the length of the string. Space complexity is O(n) with the use of char array during the algorithm.

    Accepted code:

     1 //1RE, 1AC, special case needs special handling
     2 class Solution {
     3 public:
     4     string convert(string s, int nRows) {
     5         // IMPORTANT: Please reset any member data you declared, as
     6         // the same Solution instance will be reused for each test case.    
     7         
     8         // 1RE here, ignored the special case where nRows == 1
     9         if(nRows == 1){
    10             return s;
    11         }
    12         char *str = nullptr;
    13         int i, j, k, len;
    14         
    15         len = s.length();
    16         str = new char[s.length() + 1];
    17         j = 0;
    18         for(k = 0; k < nRows; ++k){
    19             if(k == 0){
    20                 for(i = 0; i < len; ++i){
    21                     if(i % (2 * nRows - 2) == 0){
    22                         str[j++] = s[i];
    23                     }
    24                 }
    25             }else if(k == nRows - 1){
    26                 for(i = 0; i < len; ++i){
    27                     if(i % (2 * nRows - 2) == nRows - 1){
    28                         str[j++] = s[i];
    29                     }
    30                 }
    31             }else{
    32                 for(i = 0; i < len; ++i){
    33                     if(i % (2 * nRows - 2) == k || i % (2 * nRows - 2) == 2 * nRows - 2 - k){
    34                         str[j++] = s[i];
    35                     }
    36                 }
    37             }
    38         }
    39         str[j] = 0;
    40         
    41         string res = string(str);
    42         delete[] str;
    43         return res;
    44     }
    45 };
  • 相关阅读:
    centos安装nginx
    Vue练习十一:02_05_函数传参改变Div任意属性的值
    Vue练习十:02_04_弹出层
    Vue练习九:02_03_求数组中所有数字的和
    Vue练习八:02_02_点击div显示内容
    Vue练习七:02_01_百度输入法
    Vue练习六:01_06_记住密码提示框
    Vue练习五:01_05_鼠标移入改变样式鼠标移出恢复
    Vue练习四:01_04_点击将DIV变成红色
    Vue练习三:01_03_函数传参
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3453009.html
Copyright © 2020-2023  润新知