Created
June 22, 2018 08:48
-
-
Save anantham/b1191443e5c6b613ed802f8e4953f747 to your computer and use it in GitHub Desktop.
Java solution to the CrossCharacter problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Cross character solution | |
import java.util.Scanner; | |
import java.util.ArrayList; | |
public class CrossCharacter { | |
public static void main(String[] a) { | |
Scanner in = new Scanner(System.in); | |
System.out.println("Enter the number of test cases"); | |
int t = in.nextInt(); | |
System.out.println("enter all the "+t+" test cases line by line"); | |
ArrayList<String> input = new ArrayList<String>(); | |
in.nextLine(); | |
for(int i = 0; i<t; i++){ | |
input.add(in.nextLine()); | |
} | |
System.out.println("the input is: "+input); | |
for(int i = 0; i<t; i++){ | |
//consider the ith test case | |
int l = input.get(i).length(); | |
boolean flag = true; | |
for(int j = 0, before = 0, after = l-1; j<l; j++){ | |
char c = input.get(i).charAt(j); | |
// passed capacity to it | |
StringBuilder sb = new StringBuilder(l-1-j); | |
for (int k = 0; k < after; k++){ | |
sb.append(" "); | |
} | |
String spaceAfter = sb.toString(); | |
StringBuilder sbt = new StringBuilder(l-1-j); | |
for (int k = 0; k < before; k++){ | |
sbt.append(" "); | |
} | |
String spaceBefore = sbt.toString(); | |
if(after == 0){ | |
System.out.println(spaceBefore+c+c); | |
flag = false; | |
} | |
else if (after == -1){ | |
System.out.println(spaceBefore+c); | |
flag = false; | |
} else{ | |
System.out.println(spaceBefore+c+spaceAfter+c); | |
} | |
//update space numbers | |
if(flag){ | |
after = after - 2; | |
before = before + 1; | |
}else{ | |
after = after + 2; | |
before = before - 1; | |
} | |
} | |
} | |
in.close(); | |
System.exit(0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Problem statement given here - https://practice.geeksforgeeks.org/problems/cross-character/0