Rachamalla Kavya Sri Rachamalla Kavya Sri - 3 months ago 18
Java Question

Expression error detector [PARSER]

I have a question on parser, whenever a user enters the expression like

(a+b*c(d-e)
, He forgot to enter the other closing brace, and the program should give an error like
It's a wrong Expression
. Please help me out in doing this program, I have no idea how to start.

Answer

Use a stack data structure to validate the parenthesis matching.

If the character is '(','{','[' push the character onto the stack if the character is ')','}',']' respectively for the matching opening bracket then pop. Continue this till the stack is empty.

Code:

 import java.util.*;

 class ParenthesisMatching
 {
    public static void main(String[] args) 
    {
        Scanner scan = new Scanner(System.in);
        Stack<Integer> stk = new Stack<Integer>();
        System.out.println("Enter expression");
        String exp = scan.next();        
        if(isValid(exp))
            System.out.println("matched");
        else System.out.println("unmatched");
    }

    public static boolean isValid(String s) {
        HashMap<Character, Character> map = new HashMap<Character, Character>();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');

        Stack<Character> stack = new Stack<Character>();

        for (int i = 0; i < s.length(); i++) {
            char curr = s.charAt(i);

            if (map.keySet().contains(curr)) {
                stack.push(curr);
            } else if (map.values().contains(curr)) {
                if (!stack.empty() && map.get(stack.peek()) == curr) {
                    stack.pop();
                } else {
                    return false;
                }
            }
        }

        return stack.empty();
    }  
 }
Comments