A 24ms C++ Solution with Comments


  • 0
    Y
    class Solution {
    public:
        string convert(string s, int numRows) {
            int len = s.length();
            /*if s is "" or no zigzag or row count is larger than size of string, then just input original string*/
            if((!len)||(numRows == 1)||(len <= numRows)) return s; 
            /*I define a block as a pattern of the zigzag, then count the number of blocks according to string length*/
            int countBlock = ceil(len * 1.0 / (2*numRows - 2));
            vector<char> str;
            string ans = "";
            for(int i = 0; i < numRows; i++) {
                for(int j = 0; j < countBlock; j++) {
                    /*All the elements contained in blocks should less than string length*/
                    if(((2*numRows - 2)*j + i) < len) {
                        /*The index does not come to the top or bottom of row, only push back 2 char that is in the same row*/
                        if((i != 0)&&(i != numRows - 1)) {
                            /*Push back the char that is in the vertical line*/
                            str.push_back(s[(2*numRows - 2)*j + i]);
                            /*If the index does not exceed length, push back the char that is in the incline line*/
                            if(((2*numRows - 2)*j + 2*(numRows - i - 1) + i) < len) str.push_back(s[(2*numRows - 2)*j + 2*(numRows -i -1) + i]);
                        /*If index comes to the top or bottom of row, only push back 1 char*/
                        } else str.push_back(s[(2*numRows - 2)*j + i]);
                    }
                }
            }
            for(int m = 0; m < str.size();m ++) {
                ans += str[m];
            }
            return ans;
        }
    };

Log in to reply
 

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