OJ练习5——T6

ZigZag Conversion

输入一串字符,(由上到下再由下向上)Z字形循环排列后,逐行打印输出。

例如:输入PAYPALISHIRING 输出PAHNAPLSIIGYIR

2015.4.7重做

【我的代码】

string convert(string s,int nRows){
    int i, x, y, index;
    string res;
    x=2*n-2;
    for(i=0; i<n; i++)
    {
        index=i;
        res.push_back(s[index]);
        index+=x;
        y=2*n-2-x;
        while(index<s.size())
        {
            res.push_back(s[index]);
            if(y==0)
                index+=x;
            else{
                index+=y;
                y=2*n-2-y;
            }
        }
        x-=2;
        if(x==0)
            x=2*n-2;
    }
    return res; }

【评价】

在vs上测试,n=3、4都是正确的结果。探索了每行的下标之间的规律,还是可取的。

但是在平台上有“溢出”错误,没找到原因。

【优美的别人的代码】

string convert(string s, int nRows) {
    string res[nRows];
    int i = 0, j, gap = nRows-2;
    while(i < s.size()){
        for(j = 0; i < s.size() && j < nRows; ++j) res[j] += s[i++];
        for(j = gap; i < s.size() && j > 0; --j) res[j] += s[i++];
    }
    string str = "";
    for(i = 0; i < nRows; ++i)
        str += res[i];
    return str;
    }

【评价】

这个题目主要可以学习到字符串数组的使用

先定义每一行一个串,按原串顺序将字符一个一个顺次放到其应该在的串中。

其中,i是顺序遍历的,gap定义中间的“链接”部分,即有3行时,gap=1,4行时,gap=2.

思维是正向的,代码精简。

posted on 2015-01-15 10:09  EmmaLi  阅读(152)  评论(0编辑  收藏  举报

导航