
How to match a string symbols using the INDEX and the method use Stack it will determine balance or not balance ...use the STACK ...and it must be in priority...... -PARENTHESIS -BRACKET -BRACES
Example output:
Enter a string symbols:{()}
BALANCED
Enter a string symbols: (((((((((((((()
NOT BALANCE
Enter a string symbols: {[()]}
BALANCED
Enter a string symbols: {{{[[()
NOT BALANCE
THE SYMBOLS MUST BE PAIR WITH EACH OTHER IN PARENTHESIS,BRACKETS AND BRACES

Hi Friend,
Try the following code:
import java.util.*;
public class Match{
public static boolean check(String s) {
Stack<Character> stack = new Stack<Character>();
char p1 = '(';
char p2 = ')';
char br1 = '{';
char br2 = '}';
char bk1 = '[';
char bk2 = ']';
for (int i = 0; i < s.length(); i++){
if (s.charAt(i) == p1) stack.push(p1);
else if (s.charAt(i) == br1) stack.push(br1);
else if (s.charAt(i) == bk1) stack.push(bk1);
else if (s.charAt(i) == p2){
if (stack.isEmpty())
return false;
if (stack.pop() != p1)
return false;
}
else if (s.charAt(i) == br2){
if (stack.isEmpty())
return false;
if (stack.pop() != br1)
return false;
}
else if (s.charAt(i) == bk2){
if (stack.isEmpty())
return false;
if (stack.pop() != bk1)
return false;
}
}
return stack.isEmpty();
}
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Enter a string symbols: ");
String s = input.next();
if (check(s)== true)
System.out.println("BALANCED");
if (check(s)== false)
System.out.println("NOT BALANCED");
System.out.println();
}
}
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.