Using Map in C++


  • 0
    R

    #include <iostream>
    #include <string>

    class Solution {
    public:
    string convert(string s, int numRows) {

        int str_size = s.length();
        
        map<int,string> zigzag; // key: level; value: string for that level
        int key = 0;
        int op_flag = 0;
        string result;
        
        string tmp;
        if (str_size == 0)  //edge case
            return "";
        else if(str_size == 1) //edge case
            return s;
        else if(numRows == 1) //edge case
            return s;
        else
        {
            key = 0;
            for( int i = 0; i < str_size; i++)
            {
    
                tmp = zigzag[key]; // tmp = "" if no entry at zigzag[key]
                tmp+=s[i]; //append char
                zigzag[key]= tmp;   //the new string in the map against the key
    
                if(key == numRows-1)  
                    op_flag = 1; // operation flag to decrement key
                else if(key == 0)
                    op_flag = 0; // operation flag to increment key
    
                if (op_flag == 0) //increment
                    key++;
                else if(op_flag ==1) //decrement
                    key--;
            }
    
            //combine all the strings
            for(int i = 0; i <numRows; i++)
                result.append(zigzag[i]);
            
            return result;
        }
    }   
    

    };


Log in to reply
 

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