My C++ code beating 75% not hard to understand using mathematical thought


  • -1
    W
    string convert(string s, int numRows) {
    	string ss(s);
    	int k = -1;
    	if (numRows == 1)
    		return s;
    	for (int i = 0; i < numRows; i++){
    
    
    		int m = 2 * (numRows - i) - 2;
    		int n = 2 * (i + 1) - 2;
    		int j = i;
    		ss[++k] = s[i];
    		if (m == 0)
    			while (j+n < s.size()){
    				j += n;
    				ss[++k] = s[j];
    			}
    		else if (n == 0){
    			while (j+m < s.size()){
    				j += m;
    				ss[++k] = s[j];
    			}
    		}
    		else
    			while (j<s.size()){
    				j += m;
    				if (j >= s.size())
    					break;
    				ss[++k] = s[j];
    			
    
    				j += n;
    				if (j >= s.size())
    					break;
    				ss[++k] = s[j];
    			}
    
    		}
    	
    	ss[s.size()] = '\0';
    
    	return ss;
    }
    

    Here is my C++ code , i tried so many times and got Runtime error most of time while i run the same case in my VS2013 correctly . In the end i tried this and i got correct.


Log in to reply
 

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