In: Computer Science
Write Java code that prompts the user for a string and tells them if the grouping characters in that string are balanced. Grouping characters are ( and ), [ and ], and { and }. I got the basic idea for this problem from HackerRank. It’s also a very common interview question.
*******************8Example output**************
Enter the expression:{[()]} {[()]}
is balanced
Enter the expression: {()()} {()()}
is balanced
Enter the expression: {([[])} {([[])}
is not balanced
Enter the expression: {([)]} {([)]}
is not balanced
Iterate over each parantheses from start to end and do the below step at each iteration.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class Parantheses {
public static void main(String args[]){
Scanner sc = new Scanner(System.in); //enter the input expression
System.out.print("Enter the expression:");
String inputString = sc.nextLine();
System.out.println(checkBraces(inputString));
sc.close();
}
static String checkBraces(String v){
Stack
String r = "is not balanced"; // initialization of variables
char tmpChar;
Character[] openingBraces = {'[','(','{'};
Character[] closingBraces = {']',')','}'};
List
List
if(v == null){
return r;
}else if(v.length()==0)
{ //v is value
r = " is balanced";
}else{
for(int i=0; i < v.length(); i++) {
tmpChar = v.charAt(i);
if(openingBracesList.contains(tmpChar)){
charstack.push(tmpChar);
}else if(closingBracesList.contains(tmpChar)){
if(!charstack.isEmpty()){
if(tmpChar==')' && '(' != charstack.pop()){
return r;
}else if(tmpChar=='}' && '{' !=charstack.pop()){ //poping character
return r;
}else if(tmpChar==']' && '[' != charstack.pop()){
return r;
}
}else{
return r;
}
}else{
return r;
}
}
}
if( charstack.isEmpty()){
r = " is balanced";
return r;
}else{
return r;
}
}
}
output is: