Simple Readable Java Solution using Matrix


  • 0
    G

    ...

    public String convert(String input, int rows) {
    	//Create an array of size where columns is string length and rows is rows		
    	char value[][] = new char[rows][input.length()];
    	
    	int index = 0;
    	boolean goDown = true;
    	int i=0,j=0;
    	
    	
    	if(input==null||input.length()==0 || rows==1){
    		return input;
    	}
    	
    
    	
    	while(index<=input.length()-1) {
    		char charValue = input.charAt(index);
    		if(i==0 ) {
    			goDown=true;
    		}
    		else if(i==rows-1) {
    			goDown=false;
    		}	
    		value[i][j] =charValue;
    		System.out.println("value["+i+"]["+j+"]="+charValue);
    
    		if(goDown) {
    			i++;
    		}
    		else {
    			i--;
    		}			
    		j++;
    		index++;
    	}
    	
    	StringBuilder sb = new StringBuilder();
    	
    	for(int k=0;k<value.length;k++) {
    		 for(int m=0;m<value[k].length;m++) {
    			 int blank = value[k][m];
    			 if(blank==0) {
    				 continue;
    			 }
    			 else {
    				 sb.append(value[k][m]) ;
    			 }
    		 }
    		
    	}
    	System.out.println(sb.toString());
    	return sb.toString();
         
    }
    

    ...


Log in to reply
 

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