Java balanced expressions check {[()]}

后端 未结 30 1156
傲寒
傲寒 2020-12-04 17:17

I am trying to create a program that takes a string as an argument into its constructor. I need a method that checks whether the string is a balanced parenthesized expressio

30条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 17:46

    ///check Parenthesis
    public boolean isValid(String s) {
        Map map = new HashMap<>();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        Stack stack = new Stack<>();
        for(char c : s.toCharArray()){
            if(map.containsKey(c)){
                stack.push(c);
            } else if(!stack.empty() && map.get(stack.peek())==c){
                stack.pop();
            } else {
                return false;
            }
        }
        return stack.empty();
    }
    

提交回复
热议问题