24 ms Cpp simple solution. Any improvement?

  • 0

    I created an array of string for each row, append them with each character from the input s in order.
    For example, if the number of rows are 3, so the order to append the string would be: 1,2,3,2,1,2,3, etc.

    At the end, append those string for each row together.

    class Solution{
    	std::string convert(std::string s, int numRows){
    		//use case
    		if(numRows <= 1) return s;
    		// create array of string
    		std::string *stringPerRow = new std::string[numRows];
    		std::string result;
    		bool up = true;
    		int row = 0;
    		// start to iterate for each character
    		for(std::string::size_type i =0; i< s.size(); i++)
    			stringPerRow[row] += s[i];
    			if(up) row++;
    			else row--;
    			if(row == numRows){ row-= 2; up = false;}
    			if(row == 0){up = true;}
    		//append all string into one result
    		for(int i = 0; i < numRows; i++)
    		delete [] stringPerRow;
    		return result;

Log in to reply

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