Java Solution


  • 0
    L
    public class ZigZagConvertion {
        public String convert(String s, int numRows) {
            if(numRows == 1){
                return s;
            }
            if(s.equals("")){
                return s;
            }
            int n = s.length();
            int numColumns = (1+n/(2*numRows-2))*(numRows-1);
            char[][] charArray = new char[numRows][numColumns];
            StringBuilder zigzagString = new StringBuilder();
            int start = 0;
            for(int columnIndex=0;columnIndex<numColumns;columnIndex++){
                for(int rowIndex=0;rowIndex<numRows;rowIndex++){
                    if(start == n){
                        break;
                    }
                    if((columnIndex%(numRows-1)==0) ||((columnIndex+rowIndex)%(numRows-1))==0){
                        charArray[rowIndex][columnIndex]=s.charAt(start++);
                    }
                    else{
                        charArray[rowIndex][columnIndex]=Character.MIN_VALUE;
                    }
                }
            }
    
            for(int rowIndex=0;rowIndex<numRows;rowIndex++){
                for(int columnIndex=0;columnIndex<numColumns;columnIndex++){
                    if(((columnIndex%(numRows-1)==0) ||((columnIndex+rowIndex)%(numRows-1))==0) && charArray[rowIndex][columnIndex]!=Character.MIN_VALUE)
                    {
                    zigzagString.append(charArray[rowIndex][columnIndex]);
                    }
                }
            }
    
            return zigzagString.toString();
    
    
        }
    }
    
    

Log in to reply
 

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