Accepted C++ solution for Zigzag conversion.


  • 0
    R

    Following is my accepted code for zigzag conversion problem .

    class Solution {
        public:
            string convert(string input, int numrows) {
                string output="";
                
                int len = input.length();
                //special case
                if(numrows >= len || numrows == 1)
                        return input;
        
                //create a parallel array of zigzag sequence
                int seq[len];
                bool rev = false; //direction of printing
        
                for(int i=0,j=0;i<len;i++) {
                        seq[i] = j;
                        if(j == numrows - 1)  
                                rev  = true;
                        if(j == 0 )
                                rev = false;
                        if(rev)
                         j--;
                        else
                         j++;
                }
                   
                //assign row-wise characters from parent string to output
                for(int j=0,k=0;j<numrows;j++) {
        
                        for(int i=0;i<len;i++){
                                if(seq[i]== j)
                                        output += input[i];
                        }
                }
               
                return output;
                
            }
        };

  • 0

    what is your runtime?


Log in to reply
 

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