zoukankan      html  css  js  c++  java
  • LeetCode-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".

    所谓的ZigZag,就是这样的:(P.S:某些浏览器的高速模式可能看不到图,兼容或IE模式应该可以)

      因为这是有规律的,可以用数学公式计算出下一个数组下标,这样节省了一定的空间和时间。 题目的输出是按行来拼接字符的,

      因此我们可以通过逐行计算下标,拼接字符来达到目的。

     

    实现代码:

    char* convert(char* s, int numRows) {
      int num = strlen(s);
        if(numRows <=1 || num <= numRows)
            return s;
        char *result = (char *)malloc(num+1);
        int i,skip,index,j =0;
        for(i = 0; i < numRows; i++)
        {
            if(i == numRows-1)
                skip = 2*(numRows-1);
            else
                skip = numRows-1;
            index = i;
            while(index < num)
            {
                result[j++] = s[index];
                index +=(skip-index)*2;
                if(i == numRows-1 || i == 0 )
                    skip += 2*(numRows-1);
                else
                    skip += numRows-1;
            }
        }
        result[num] = 0;
        return result;
    }
  • 相关阅读:
    gym-102307 D. Do Not Try This Problem
    AtCoder Beginner Contest 161 E
    Codeforces 1270E 构造+数学
    2019牛客暑期多校训练营(第七场)E 线段树+离散化区间
    codeforces 1272F dp+记录路径
    Focus相关点滴
    Command模式
    接口隔离原则(ISP)
    依赖倒置原则(DIP)
    Liskov替换原则(LSP)
  • 原文地址:https://www.cnblogs.com/neyer/p/4608506.html
Copyright © 2011-2022 走看看