1/*
2PARENTHESE MATCHING
3AUTHOR: UTKARSH SINHA
4*/
5bool correct_paranthesis(string str){
6 stack<char> stk;
7 map<char,char> bracket_map;
8 bracket_map[')'] = '(';
9 bracket_map['}'] = '{';
10 bracket_map[']'] = '[';
11
12 for(int i=0; i<str.size(); i++){
13 if(str[i] == '(' || str[i] == '{' || str[i] == '[')
14 stk.push(str[i]);
15 if(str[i] == ')' || str[i] == '}' || str[i] == ']'){
16 if(stk.empty())
17 return false;
18 if(stk.top() == bracket_map[str[i]] )
19 stk.pop();
20 }
21 }
22
23 return (stk.empty() == true);
24}
1import java.util.Scanner;
2import java.util.ArrayList;
3public class BalanceBracket {
4public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.println("enter a string with '(', '{' or '['");
7 String s = sc.nextLine();
8 String y = isBalanced(s);
9 System.out.println(y);
10}
11static String isBalanced(String s)
12{
13 String result = "NO";
14 ArrayList<String> al = new ArrayList<String>();
15
16 for(int i = 0; i < s.length(); i++)
17 {
18 if(s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[')
19 {
20 al.add(Character.toString(s.charAt(i)));
21 }
22
23 else if(s.charAt(i) == ')' || s.charAt(i) == '}' || s.charAt(i) == ']')
24 {
25 if(al.size() != 0 && al.get(al.size()-1).equals("(") && s.charAt(i) == ')')
26 {
27 al.remove(al.size()-1);
28 }
29 else if(al.size() != 0 && al.get(al.size()-1).equals("{") && s.charAt(i) == '}')
30 {
31 al.remove(al.size()-1);
32 }
33 else if(al.size() != 0 && al.get(al.size()-1).equals("[") && s.charAt(i) == ']')
34 {
35 al.remove(al.size()-1);
36 }
37 else
38 {
39 return result = "NO";
40 }
41 }
42
43 }
44 if(al.isEmpty() == true)
45 {
46 return result = "YES";
47 }
48 return result;
49}
50}
1// for Java
2
3class Parser{
4 static HashMap<Character,Character> bracket_map = new HashMap<>();
5
6 static {
7 bracket_map.put(')', '(');
8 bracket_map.put('}','{');
9 bracket_map.put(']','[');
10 }
11
12 boolean isBalanced(String s){
13
14 Stack<Character> stack = new Stack<>();
15 char temp;
16 for (int i = 0; i < s.length(); i++) {
17 temp = s.charAt(i);
18 if(temp == '{' || temp == '[' || temp == '('){
19 stack.push(temp);
20 }else {
21 if(stack.isEmpty() || stack.peek() != bracket_map.get(temp)) return false;
22 stack.pop();
23 }
24 }
25 return stack.isEmpty();
26 }
27}