In: Computer Science
JAVA question
A string may use more than one type of delimiter to bracket information into "blocks". The primary ways to divide things up into block is by the braces { } , parentheses ( ), and brackets [ ] as delimiters.
SOLUTION-
I have solve the problem in Java code with comments and screenshot
for easy understanding :)
CODE-
//java code
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main (String[] args) {
// createan object of Scanner class for user input
Scanner sc = new Scanner(System.in);
// get the string from the user
System.out.print("Enter String : ");
String exp = sc.next();
// create stack which stores the braces from the string that are
enetered by the user
Stack<Character> stack = new Stack<>();
// now get each char from the string
for(int i=0; i<exp.length(); i++){
// read char by char using charAt() method
char ch = exp.charAt(i);
// if character is belongs to any braces then use stack. otherwise
continue
if(ch == '{' || ch == '[' || ch == '(' || ch == ')' || ch == ']' ||
ch == '}'){
// check whether stack is empty then push the braces to the
stack
if(stack.isEmpty()){
// character is added to the stack using push() method
stack.push(ch);
}else{
// When stack contain open braces and character of string contain
same closed braces then pop that braces from the stack
if(ch == '}' && stack.peek() == '{' || exp.charAt(i) == ')'
&& stack.peek() == '(' || exp.charAt(i) == ']' &&
stack.peek() == '['){
// pop() same braces from the stack using pop() method
stack.pop();
}else{
// if there is no braces that same closed with top of the stack
then add that character to the stack
stack.push(ch);
}
}
}
}
/*
After all the operation if stack is empty
then our string is good otherwise bad
*/
if(stack.isEmpty()){
// print in console that string is "good" because stack is
empty
System.out.println("good");
}
else{
// print in console that string is "bad" because stack is not
empty
System.out.println("bad");
}
}
}
SCREENSHOT-
Test few strings that are "good" and "bad".
1> When string is "good".
2> When string is "good".
3> When string is "good".
4> When string is "bad".
5> When string is "bad".
6> When string is "good".
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I WILL
SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------