23ms Solution in C++


  • 0
    K
    class Solution {
    public:
        string convert(string s, int numRows) {
        string res;
        if(numRows<=1) return s;
    
        if (s.length()==0) {
            return res;
        }
    
        for (int i=0; i<numRows; i++) {
            for (int j=0,index=i; index<s.length(); j++,index =(2*numRows-2)*j+i) {
                res+=s[index];
         //add the vertical elements behind the result str
    
    
    
                if ((index+(numRows-i-1)*2)<s.length()&&i!=0&&i!=numRows-1) {
                    res+=s[index+(numRows-1-i)*2];
          //add the diagonal elements behind the result str
                }
            }
        }
    
        return res;
        }
    };
    

    As another friend below said, using a StringBuilder instead of String to do the concatenating work is a better option in memory cost.


  • 1
    H

    Because a string is immutable and you are concatenating strings. Each concat creates a new string. Use StringBuilder instead.


  • 0
    K

    yes, u r right buddy. But then I found I forgot to deal with the situation that numRows<=1, either


Log in to reply
 

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