leetcode 6: ZigZag Conversion

In one line, the first character is s[i], the second is s[i+2*numRows-2-2*i] and the third is s[i+2*numRows-2]. Just be careful with the test cases that numRows==1 and numRows>len.

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows==1)
            return s;
        int len=s.length();
        string res;
        for(int i=0;i<numRows;i++)
        {
            int curr=i;
            if(curr>=len)
                break;
            res.push_back(s[curr]);
            int step1=(2*numRows-2)-2*i;
            int step2=2*i;
            while(1)
            {
                curr+=step1;
                if(curr>=len)
                    break;
                if(step1)
                    res.push_back(s[curr]);
                curr+=step2;
                if(curr>=len)
                    break;
                if(step2)
                    res.push_back(s[curr]);
            }
        }
        return res;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章