Java怎么实现有效的括号

本篇内容介绍了“Java怎么实现有效的括号”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', 
determine if the input string is valid.

The brackets must close in the correct order, 
"()" and "()[]{}" are all valid but "(]" and "([)]" are not.
public class Solution {
    public 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.containsKey(curr)){
                stack.push(curr);
            } else if (map.containsValue(curr)) {
                if (!stack.isEmpty() && map.get(stack.pop()).equals(curr)){
                    continue;
                } else {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}

“Java怎么实现有效的括号”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!