【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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值