My AC code, store it in a matrix


  • 0
    E

    use row strings to simulate a matrix.

    1.store s in a matrix.
    zig part: read row values out s sequentially from 0 ~ row-1
    zag part: read row-2 values out of s reversely from row-2~1

    1. combine the strings and output the result
     string convert(string s, int nRows) {
        	 vector<string> matrix(nRows,"");
    
        	 //1.convert s into matrix
        	 int i=0,j;
        	 while( i<s.size() ){
        		 for(j=0;j<nRows;j++){ //zig
        			if(i>=s.size())break;
        			matrix[j].push_back(s[i++]);
        		 }
        		 
        		for(j=nRows-1-1;j>=0+1;j++){//zag
        			if(i>=s.size())break;
        				matrix[j].push_back(s[i++]);
        		 }
        	 }
        
        	 //2.output matrix 
        	string result;
        	for(j=0;j<nRows;j++){
        		result.append(matrix[j]);
        
        	}
        	 return result;
         }

  • 0
    S

    Pay attention to "Writing code? Select a code block and click on the button to preserve code formatting.” above text editor.


Log in to reply
 

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