My C++ 16ms ,short and easy to understand!!


  • 1
    X
    class Solution {
    public:
        string convert(string s, int numRows) {
            if(numRows == 1 || numRows > s.length() ) return s;
            string tmp;
            string result;
            int length = s.length();
            for(int i = 0; i < numRows; ++i){
                if(i == 0 || i == numRows -1){
                    for(int j = i; j < length; j = j + 2 * (numRows -1 ) ){
                        result.push_back(s[j]);
                    }
                    continue;
                }
                int x = 2* (numRows - i -1 );
                for(int j = i; j < length; j = j+2*(numRows - 1) - x){
                    result.push_back(s[j]);
                    x = 2*(numRows - 1 ) - x;
                }
            }
            return result;
        }
    };

  • 1
    H

    Almost the same as my code except for the last part.

     std::string convert(std::string s, int numRows) {
            
            int strlen = s.length();
            int jump = 2*numRows -2;
            if (numRows == 1 || numRows > strlen) return s;
            int i, j, next;
            std::string  result;
            for (i=0; i < numRows; ++i){
                
                if (i== 0 || i == numRows -1) { //for first and last rows
                    for (j = i; j <  strlen;j += jump){
                        result.push_back(s[j]);
                    }
                    
                }else{
                    for (j = i; j < strlen; j += jump){
                        result.push_back(s[j]); //down the columns
                        next = j + jump - (2*i);
                        if ( next < strlen){
                            result.push_back(s[next]); //diagonal lines
                        }
                    }
                }
            }
            return result;
        }
        
    };

  • 0
    R

    explain it, do not copy your code .......


Log in to reply
 

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