leetcode zigzag conversion

来源:互联网 发布:java反斜杠替换 编辑:程序博客网 时间:2024/05/15 04:35


一开始实在没看懂题意。。。。 只好找找啥意思,结果一下就看到答案了,哎。

不过还是用了50行代码。看看人家,十几行搞定,真是惭愧- -

leetcode上的代码:

class Solution{public:    string convert(string s, int nRows) {        if(nRows < 2 || s.length() <= nRows) return s;        string ret = "";        for(int row=0; row<nRows; row++){            if(row == 0 || row == nRows-1){                int step = 2*nRows-2;                int index = row;                while(index < s.length()){                    ret.push_back(s[index]);                    index += step;                }            }else{                int step = 2*nRows-2;                int index = row;                while(index < s.length()){                    ret.push_back(s[index]);                    int zig_index = index + (step - 2*row);                    if(zig_index < s.length()) ret.push_back(s[zig_index]);                    index += step;                }            }        }        return ret;    }};


0 0
原创粉丝点击