Zig Zag Coversion


  • 0
    S

    Here we will take numRows vectors and push characters respective vector. We will take a variable rev(reverse) which will store the direction (Top to bottom || bottom to Top). The flag variable stores the index of vector in which we are going to push the next character of string

    class Solution {
    public:
        string convert(string s, int numRows) 
        {
            vector<int> v[numRows];
            int flag=0;
            int rev=0;
            if(numRows==1)
                return s;
            for(int i=0;i<s.length();i++)
            {
                if(rev==0)
                {
                    v[flag].push_back(s[i]);
                    if(flag==numRows-1)
                    {
                        flag=numRows-2;
                        rev=1;
                    }
                    else
                        flag=flag+1;
                        
                }
                else
                {
                    v[flag].push_back(s[i]);
                    if(flag==0)
                    {
                        flag=1;
                        rev=0;
                    }
                    else 
                        flag=flag-1;
                }
            }
            
            string ans="";
            for(int i=0;i<numRows;i++)
            {
                vector<int> vec=v[i];
                for(int j=0;j<vec.size();j++)
                    ans.push_back(vec[j]);
            }
            return ans;
        }
    };
    

Log in to reply
 

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