[leetcode]36 ZigZag Conversion


タイトルリンク:https://leetcode.com/problems/zigzag-conversion/ Runtimes:40ms
1、問題
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”.
2、分析
nRows=1の場合、元の文字列です.nRows=2の場合、2行の文字列で、元の文字は2つの文字列ごとに同行します.nRows=3の場合、1行の文字列と3行の文字列はいずれも元の文字列が4行おき、2行の文字列は元の文字列が2行おきである.nRows=nの場合、1行目の文字列とn行の文字列は、元の文字列が(n-2)*2+2(Nとする)文字列ごとに同行し、中間i行目は元の文字列がN-2 iを1回隔て、2 i文字列を1回隔てて同行する.このように推す.
3、まとめ
規則正しい変化が見られます.
4、実現
class Solution {
public:
    string convert(string s, int nRows) {
        if ("" == s || nRows == 1)
            return s;
        int n = (nRows - 2) * 2 + 2;
        string str = "";
        for (int i = 0, j = n; i < nRows; i++, j -= 2)
        {
            int index = i;
            bool isFirst = true;
            while (index < s.length())
            {
                str = str + s[index];
                if (n == j || j == 0)
                {
                    j = n;
                    index += j;
                }
                else{
                    if (isFirst)
                    {
                        index += j;
                        isFirst = false;
                    }
                    else{
                        index += (n - j);
                        isFirst = true;
                    }
                }
            }
        }
        return str;
    }
};

5、反省
もっと速く見えるようです.