Wednesday, January 8, 2014

[LeetCode] ZigZag Conversion


 
class Solution {
    public:
    string convert(string s, int nRows) {
        int n=s.size();
        if(n==0) return "";
        if(nRows==1)
        return s;
        int half = nRows-1;
        int step = half*2;
        string ret="";
        
        vector<string> v(nRows,"");
        
        for(int i=0; i<n; i+=step)
        {
            for(int j=0; j<half; j++)
            if(i+j<n) v[j]+=s[i+j];
            for(int j=0; j<half; j++)
            if(i+half+j<n) v[half-j]+=s[i+half+j];
        }
        for(int i=0; i<nRows; i++)
        ret+=v[i];
        return ret;
    }
};

No comments:

Post a Comment