[LeetCode] ZigZag Conversion

来源:互联网 发布:双界面软件手机 编辑:程序博客网 时间:2024/05/21 10:10

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)

 01234560P A H N1APLSIIG2Y I R  

P A H NAPLSIIGY 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"

Idea:  通过找规律,可以知道一个zigzag 有 2 * nRows -2 个元素。 

先放第一排和最后一排的元素。

在放之字形中间的元素


class Solution {public:    string convert(string s, int nRows) {        int size = s.size();        if(size <= 1 || nRows <= 1 || size <= nRows) return s;                string result ;                int k = 0,            zigzag = 2 *nRows - 2, //one zigzag element count            count = size/zigzag + 1;   //how many zigzag        for(int i = 0; i < nRows; i++)        {            for(int j = i; j < size; j+=zigzag)            {                result.append(1, s[j]); // first and last                if(i != 0 && i!= nRows -1 && j + zigzag - 2 *i < size)                {                    result.append(1, s[j + zigzag - 2 * i]);                }            }        }                return result;    }};



Idea: 将一维数组string[size] 转为二维数组result[nRows][ ], 然后按照行输出。

 --------------------------------Memory Limit Exceeded------------------------------------------

class Solution {public:    string convert(string s, int nRows) {        int size = s.size();        if(size <= 1 || nRows <= 1 || size <= nRows) return s;                int **p = new int* [nRows];        int nCols = (size/(2*nRows - 2) + 1)*(nRows -1);        for(int i = 0; i < nRows; i++)        {            p[i] = new int [nCols];        }                int k = 0,            row = nRows - 1;        for(int j = 0; j < nCols; j++)        {            for(int i = 0; i < nRows; i++)            {                if(!(j % row) && k < size)                {                    p[i][j] = s[k++];                }                else if(!(i + j % row) && k < size)                {                    p[i][j] = s[k++];                }                else                {                    p[i][j] = ',';                }            }        }                k = 0;        for(int i = 0; i < nRows; i++)        {            for(int j = 0; j < nCols; j++)            {                if(p[i][j] != ',')                {                    s[k++] = p[i][j];                                    }            }        }                for(int i = 0; i < nRows; i++)        {            delete [] p[i];        }                delete [] p;                return s;    }};






0 0
原创粉丝点击