Coding Challenge Day-32: Problem 2: Zigzag Conversion

Hello! So I’m doing a 30 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 32: Problem 2! Be sure to post your answers, queries etc in the comments!

Problem: ZigZag Conversion: You are given a string (str) and the number of rows (n). You need to convert it to a string in a zigzag pattern as follows:

Sample: “TechnArtBlog” ; rows=3

T n B
e h A t l g
c r o

Output: TnBehAtlgcro

Solutions:

I referred to this (LINK) while solving this one.

View on/ Download from Github (LINK)

package string;

import java.util.Arrays;

public class zigzag {
	
	public static void zz (String str, int n){
		char[] str1= str.toCharArray();
		int len= str.length();
		String [] arr= new String [n];
		Arrays.fill(arr, "");
		boolean down = true;
		int row=0;
		
		for(int i=0; i<len; i++){
			arr[row] += str1[i];
			if(row==n-1){
				down= false;
			} else if (row==0){
				down=true;
			}
			
			if(down){
				row++;
			} else {
				row--;
			}
		}
		
		for(int i=0; i<n; i++){
			System.out.print(arr[i]);
		}
		
	}
	
	public static void main (String [] args){
		String s="TechnArtBlog"; 
		zz(s, 3);
	}

}

Happy Learning!!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: