6. ZigZag Conversion
in LeetCode with 0 comment

6. ZigZag Conversion

in LeetCode with 0 comment

6. ZigZag Conversion

发现所有行的重复周期都是 2 * numRows- 2

对于首行和末行之间的行,还会额外重复一次,重复的这一次距离本周期起始字符的距离是 2 numRows- 2 - 2 i

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows == 1 || s.length() == 1)
            return s;
        string answer;
        int i, j, lag = 2 * numRows - 2;//lag循环周期
        for (i = 0; i < numRows; i++) {
            for (int j = i; j < s.length(); j += lag) {
                answer += s[j];
                //如果不是第一行或最后一行
                if (0 < i && i < numRows - 1) {
                    int t = j + lag - 2 * i;
                    if (t<s.length())
                        answer += s[t];
                }
            }
        }
        return answer;
    }
};
Responses

From now on, bravely dream and run toward that dream.
陕ICP备17001447号