Z字形Leetcode変換

タイトル説明

所与の行に従って指定した文字列の数は、ダウンに、Z型配置から左。例えば、入力文字列は、行「LEETCODEISHIRING」の数は、次のように配置され、3です。

LCIR
ETOESIIG
EDHNは、
行右に読み取りラインに左からその後、あなたは、出力を必要とするなど、新しい文字列を生成:「LCIRETOESIIGEDHN」。

思考

  1. 答えを得るために、変換プロセスをシミュレートするために暴力的な解決策が、時間がかかり、大きなメモリフットプリント
  2. 最初の文字は0、k番目の文字として定義されている場合は2つの文字間の第一法則は、最後の行であるのではなく、我々は最初の2つの文字の最後の行の間の距離は2N-3に配置されたことがわかり、法律を検索偶数番目の場合、次の文字のピッチは2 *(Nライン-1)であり、kが奇数の場合、次の文字は、距離2 *ラインです。このメソッドは文字列のみを横断するn回を必要とします

コード

この方法の一つ:

string convert(string s, int numRows) {
        int len = s.length();
        if (len<2 || numRows == 1)
            return s;
        string res;
        int numCols = len / (numRows + numRows - 2)*(numRows - 1);
        if (len % (numRows + numRows - 2) != 0)
        {
            if (len % (numRows + numRows - 2) <= numRows)
                numCols++;
            else
                numCols += 1 + len % (numRows + numRows - 2) - numRows;
        }
        vector<vector<char>> Matrix(numRows, vector<char>(numCols));
        int x = 0, y = 0;
        for (int i = 0; i<len; i++)
        {
            Matrix[x][y] = s[i];
            if (y % (numRows - 1) == 0)
            {
                if (x<numRows-1)
                    x++;
                else
                {
                    x--;
                    y++;
                }
            }
            else
            {
                y++;
                x--;
            }
        }
        for (int i = 0; i<numRows; i++)
        {
            for (int j = 0; j<numCols; j++)
            {
                if (Matrix[i][j] != '\0')
                    res += Matrix[i][j];
            }
        }
        return res;
    }

方法2:

class Solution {
public:
    string convert(string s, int numRows) {
        int len = s.length();
        if (len<2 || numRows == 1)
            return s;
        string res;
        int line = 0;
        while (line<numRows)
        {
            int index = line;
            if (line == 0 || line == numRows - 1)
            {
                while (index<s.length())
                {
                    res += s[index];
                    index = index + 2 * (numRows-1) ;
                }
                line++;
            }
            else
            {
                int count = 0;
                while (index<s.length())
                {
                    res += s[index];
                    if (count % 2 == 0)
                        index = index + 2 * (numRows - line-1);
                    else
                        index = index + 2 * line;
                    count++;
                }
                line++;
            }
        }
        return res;
    }
};
公開された85元の記事 ウォンの賞賛0 ビュー377

おすすめ

転載: blog.csdn.net/weixin_38312163/article/details/105021815
おすすめ