34ms C++ solution using custom data structure for simplicity


  • 0
    L
    class ZigZag {
    private:
        vector<string>  m_zigzag;
        int             m_rows;
        int             m_currentRow;
        int             m_dir;
    public:
        ZigZag(int rows) : m_rows(rows) , m_currentRow(0), m_dir(1) { m_zigzag.resize(m_rows);}
        
        void Add(char s)
        {
            m_zigzag[m_currentRow] += s;
            //moving up
            if (m_dir)
            {
                if (m_currentRow < m_rows - 1)
                {
                    m_currentRow++;
                }
                else
                {
                    m_dir = 0;
                    m_currentRow--;
                }
            }
            else
            {
                if (m_currentRow > 0)
                {
                    m_currentRow--;
                }
                else
                {
                    m_dir = 1;
                    m_currentRow++;
                }
            }
        }
        
        string GetString()
        {
            string answer = "";
            for (int i = 0; i < m_zigzag.size(); i++)
            {
                answer += m_zigzag[i];
            }
            return answer;
        }
    };
    
    class Solution {
    public:
        string convert(string s, int nRows) {
            ZigZag zigzag(nRows);
            if (nRows == 1)
                return s;
            for (int i = 0; i < s.length(); i++)
                zigzag.Add(s[i]);
            return zigzag.GetString();
        }
    };
    

    I have a custom class called zigzag that takes care of adding characters and printing the answer. It stores the data as a vector of strings and keeps track of the direction that the zigzag pattern is currently moving as new characters are added. Makes the actual solution a super simple loop calling into the add function for each character and then a simple call to GetString()


Log in to reply
 

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