Accepted C++ 24ms with code comments.


  • 2
    P

    I'm sure this can be optimized to reduce execution time but is how I normally would start a solution and then begin to optimize as necessary.

    class Solution {
    public:
        string convert(string s, int numRows) {
            // Array of strings based on numRows
        	vector<string> rows(numRows);
        	string answer;
        	// Flag to indicate if row increasing or decreasing?
        	bool up = false;
        	// Row counter
        	int row = 0;
        	// String length;
        	int len = s.length();
        
            // If just a single row, then return the input string
        	if(numRows <= 1)
    	    	return s;
        
            // Go character by charcter
        	for(int i = 0; i < len; i++)
        	{
        	    // append the input char into the correct string row.
        		rows[row].push_back(s[i]);
        		// Which direction are we going?
        		if(up)
        		{
        		    // We're on the zigzag diagonal going up
        			row--;
        			// Make sure we don't go negative
        			if(row < 0)
        			{
        			    // We've already used row 0 so go to row 1
        				row = 1; 
        				// We're switching directions now
        				up = false;
        			}
        		}
        		else
        		{
        		    // We're not in the zigzagt diagonal and going down
        			row++;
        			// Make sure we haven't exceeded the number of rows allowed
        			if(row >= numRows)
        			{
        			    // Yes, back up a row and start going up
        				row = numRows - 2;
        				up = true;
        			}
        		}
        	}
        
            // Append the rows together and return the resulting string
        	for(int i = 0; i < numRows; i++)
        		answer.append(rows[i]);
    
    	return answer;
        }
    };

Log in to reply
 

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