6. ZigZag Conversion (Easy)

Zigzag:即循环对角线结构

0       8       16      
1     7 9     15 17      
2   6   10   14   18      
3 5     11 13     19      
4       12       20      

向下循环:nRows

斜角线循环:nRows-2(减去首尾两个端点)

重复


Solution 1: 结果正确,但超时了

class Solution {
public:
    string convert(string s, int numRows) {
        int ilength = s.length();
        int gap = 2*numRows - 2;
        string sresult; //resulted string
        
        int i;
        
        if(ilength <= numRows || numRows == 1)
        {
            return s;
            
        }
            for ( i = 0; i <= numRows; i ++)
        {
            int ipoint = i; //current location in string s,range in (0,numRows)
            int ichange = 1; //lable two kinds of steps
            int step1 =  gap - 2*i;
             int step2 = 2*i;
            sresult += s[ipoint];
           while(sresult.length() < ilength)
           {
            if(ichange)
            {
                ipoint +=  step1;
                sresult += s[ipoint];
                ichange = 1 - ichange;
            }
            else
            {
                ipoint += step2;
                sresult += s[ipoint];
                ichange = 1 - ichange;
            }
           }
        }
        
        return sresult;
        
    }
};

Solution 2:一种效率较高的做法

class Solution {
public:
    string convert(string s, int numRows) {
       if(numRows == 1) return s;
    vector<string> res(numRows);
    int i = 0, j, gap = numRows-2;
    while(i < s.size()){
        for(j = 0; i < s.size() && j < numRows; ++j)
        {
            res[j].push_back( s[i++]);
        }
        for(j = gap; i < s.size() && j > 0; --j)
        {
            res[j].push_back( s[i++]);
        }
    }
    string str = "";
    for(i = 0; i < numRows; ++i)
        str += res[i];
    return str;}

把每一行设为一个string向量,共numRows行(行号从0开始)
按照zigzag的顺序,先给每一行依次读取一个数据,中间过渡的行有gap=numRows-2行,倒着回去从第gap行到第1行(行号从0开始)依次再读取数据,直至到s的末尾。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值