C++ solution with zigzag by vector.


  • 0
    F

    it will be easy with 2d vector,and forget zigzag. In vector it's just one by one char in different lines.

    class Solution {
    public:
    string convert(string s, int numRows) {
        if(numRows==1) return s;
        int n = s.length(),back=0,sign=1;
        string res="";
        vector<vector<char> > map(numRows);
    
        for(int i=0; i<n; i++){
            if(i!=0&&(back==numRows-1||back==0))
                sign = -sign;
            map[back].push_back(s[i]);
            if(sign==1){
                back++;
            }else{
                back--;
            }
        }
        for(int i=0; i<numRows; i++){
            for(int j=0; j<map[i].size(); j++){
                res = res + map[i][j]; 
            }
            
        }
        return res;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.