LeetCode | 6. ZigZag Conversion(之字形变换)

来源:互联网 发布:php抽象类可以实例化吗 编辑:程序博客网 时间:2024/04/29 10:44

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”.

解题思路:两种.最初想到的是开一个数组,每次像蛇形矩阵一样对数组赋值,最后对每一行每一列遍历,提取出不是空的字符.125ms,几乎是所有题叫中所有提交中最慢的之一了.
第二种,找规律,直接按0~r行,空间复杂度为O(1).29ms(参考LeetCode代码)
虽然这两个算法的复杂度都是O(n),时间差别还挺大.
/*n=numRows
Δ=2n-2 1 2n-1 4n-3
Δ= 2 2n-2 2n 4n-4 4n-2
Δ= 3 2n-3 2n+1 4n-5 .
Δ= . . . . .
Δ= . n+2 . 3n .
Δ= n-1 n+1 3n-3 3n-1 5n-5
Δ=2n-2 n 3n-2 5n-4
*/

//125msclass Solution {public:    string convert(string s, int r)     {        int len = s.length();        string res = "";        if (r == 1)            return s;        else if (r == 2)        {            for (int i = 0; i < len; i += 2)                res += s[i];            for (int j = 1; j < len; j += 2)                res += s[j];            return res;        }        char chess[1000][1000] = {};        for (int i = 0; i < r; i++)            for (int j = 0; j < len; j++)                chess[i][j] = ' ';//初始化        int it = 0, row = 0, col = 0;        while (it < len)        {            chess[row][col] = s[it];            if (row == 0)                row++;            else if (row == r - 1)            {                row--; col++;            }            else if (col % (r - 1) == 0)                row++;            else            {                row--; col++;            }            it++;        }        for (int i = 0; i < r; i++)            for (int j = 0; j <= col; j++)                if (chess[i][j] != ' ')                    res += chess[i][j];        return res;    }};
//29msclass Solution {public:    string convert(string s, int r)     {        string result = "";        if (r == 1)            return s;        int step1, step2;        int len = s.size();        for (int i = 0; i<r; ++i)         {            step1 = (r - i - 1) * 2;            step2 = (i) * 2;            int pos = i;            if (pos<len)                result += s[pos];            while (1)             {                pos += step1;                if (pos >= len)                    break;                if (step1)                    result += s[pos];                pos += step2;                if (pos >= len)                    break;                if (step2)                    result += s[pos];            }        }        return result;    }};
1 0