Solving the Zig Zag pattern problem with 2D Array in Java


  • 0
    D

    public class Solution {
    public String convert(String s, int numRows) {
    if ( s.length() == 0 || s.isEmpty() ) return "";
    if ( s.length() == 1 || s.length() == 2 || s.length() <= numRows || numRows <= 1) return s;//Return back the original string in extreme scenarios

        	int  i = 0;//index for traversing the string
        	
        	int singleNumberIndex = numRows - 2;//index for diagonal elements in the zig zag pattern
        	
        	int columnUpperBound = 0;//defines the upperbound on the number of columns needed in a 2D array
        	if ( s.length() % 2 == 0 ){//Depending on whether the string is odd or even, we will get an upperbound on columns
        	    columnUpperBound = s.length() / 2;
        	}else{
        	    columnUpperBound = ( s.length() + 1 ) / 2;
        	}
        	/*
        	** Creating a 2D Array to store the zig zag pattern
        	*/
        	char[][] twoDimArray = new char[numRows][columnUpperBound];
    
    
        		for ( int col = 0; col <  columnUpperBound; col++ ){
        			if ( col % (numRows - 1) == 0){//Vertical elements will be divisible by numRows
        				for ( int row = 0; row < numRows; row++ ){
        					if ( i < s.length() ){//Break the loop if complete string is parsed
        						twoDimArray[row][col] = s.charAt(i);
        						i++;
        						singleNumberIndex = numRows - 2;//Re-initialize for next iteration
        					} else{
        						break;
        					}
        				}
        			}else{ //Find a way to fill up middle elements in zig zag pattern
        				if ( i < s.length() && singleNumberIndex >= 1){//Total middle or diagonal elements would be n-2
    						twoDimArray[singleNumberIndex][col] = s.charAt(i);
        					i++;
        					singleNumberIndex--;
        				} else{
        					break;
        				}
        			}
        		}
        	
            /*
        	** Parse the 2D array to output the desired String
        	*/
        	StringBuffer sb = new StringBuffer();
        	for ( int firstIndex = 0; firstIndex < numRows; firstIndex++ ){
        		for ( int secondIndex = 0; secondIndex < columnUpperBound ; secondIndex++){
        			if ( twoDimArray[firstIndex][secondIndex] != 0 ){
        				sb.append( twoDimArray[firstIndex][secondIndex] );
        			}
        		}
        	}
        	return sb.toString();
        }
    }

Log in to reply
 

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