AC Java solution


  • 0
    G

    My idea is to put all the letters in a matrix and then read them line by line and get what we want.

    	public static String convert(String s, int numRows){
    		if(numRows==1){ return s; }
    		char [][]table=new char[numRows][s.length()];
    		int i=0,row=0,col=0;
    		while(i<s.length()){//put letters in a matrix
    			for(row=0;row<numRows && i<s.length();){
    				table[row++][col]=s.charAt(i++);
    			}
    			col++;
    			for(row=numRows-2;row>0 && i<s.length();){
    				table[row--][col]=s.charAt(i++);
    			}
    			col++;
    		}
    		String result="";// read the matrix
    		for(int r=0;r<table.length;r++){
    			for(int c=0;c<table[r].length;c++){
    				if(table[r][c]!='\0'){ result+=table[r][c];  }
    			}
    		}
    		return result;
    	}

Log in to reply
 

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