【leetcode】6. ZigZag Conversion

@requires_authorization
@author johnsondu
@create_time 2015.7.10 10:35
@url https://leetcode.com/problems/zigzag-conversion/
/** * 对于此题,只需要找出对应的字母所在的编号与Z型编码的关系。 * 对于第一行和最后一行进行单处处理。 * 而对中间的numRows-2行,则分奇数列和偶数列进行推导。 * 奇数列从下往上,偶数列从上往下。 * 时间复杂度(O(n)) * 空间复杂度(O(1)) */
class Solution {
public:
    string convert(string s, int numRows) {
        // return if numRows == 1
        if(numRows < 2) return s;

        string ans = "";
        int len = s.size();
        int idx = 0;
        // Process the first line
        while(idx < len){
            ans = ans + s[idx];
            idx = idx + (numRows-1) * 2;
        }
        // Process 2-numRows line
        for(int i = 1; i < numRows - 1; i ++)
        {
            // flag: Distinguish the odd and the even column
            bool flag = false;
            idx = i;
            if(idx >= len) break;
            ans += s[i];
            while(idx <= len){
                if(!flag) {
                    idx = idx + (numRows - i - 1) * 2;
                    if (idx < len) ans += s[idx];
                    flag = true;
                }
                else{
                    idx = idx + i * 2;
                    if(idx < len) ans += s[idx];
                    flag = false;
                }
            }
        }
        // Process the last line
        idx = numRows - 1;
        while(idx < len){
            ans = ans + s[idx];
            idx = idx + (numRows - 1) * 2;

        }
        return ans;
    }
};

你可能感兴趣的:(LeetCode,Algorithm,ZigZag)