My simple 20ms cpp solution


  • 0
    T
    class Solution {
    public:
        string convert(string s, int numRows) {
            if(numRows == 1) return s;
            int t = 2 * (numRows - 1);
            string result;
            int x = 0;
    
            //First Line
            while(x < s.size())
            {
                result += s[x];
                x += t;
            }
    
            //Build string directly
            for(int i = 1; i < numRows - 1; ++i)
            {
                x = i;
                while(x < s.size())
                {
                    result += s[x];
                    if(x + t - 2 * i < s.size()) result += s[x + t - 2 * i];
                    x += t;
                }
            }
    
            //Last Line
            x = numRows - 1;
            while(x < s.size())
            {
                result += s[x];
                x += t;
            }
            return result;
        }
    };
    

    I think the time complexity is O(n)


Log in to reply
 

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