[LeetCode] Zigzag Conversion

The key challenge to this problem is to make the code clean. This post has shared a nice example, which is rewritten below in C++.

class Solution {
public:
    string convert(string s, int numRows) {
        vector<string> vs(numRows, "");
        int n = s.length(), i = 0;
        while (i < n) {
            for (int j = 0; j < numRows && i < n; j++)
                vs[j].push_back(s[i++]);
            for (int j = numRows - 2; j >= 1 && i < n; j--)
                vs[j].push_back(s[i++]);
        }
        string zigzag;
        for (string v : vs) zigzag += v;
        return zigzag;
    } 
};

 

posted @ 2015-09-14 14:53  jianchao-li  阅读(219)  评论(0编辑  收藏  举报