[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".

这个题目可以通过数学计算,直接得出每行该有的序列编号的。这里用的是一种别的方法。

class Solution {
public:
    string convert(string s, int nRows) {
        if(s.empty() || nRows == 1)   return s;
        string result;
        bool ins = true;
        vector<string> res(nRows);
        int index = 0;
        int n = s.size();
        int i = 0;
        while(1)
        {
            res[i] += s[index++];
            if(index == n)  break;
            ins ? i++:i--;
            if(index % (nRows-1) == 0)
                ins = !ins;
        }
        for(auto val:res)
            result += val;
        return result;
    }
};


你可能感兴趣的:([LeetCode] ZigZag Conversion)