LeetCode 20 Valid Parentheses

题目:

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

解答:

简单的括号匹配,使用栈,遇到左括号进栈,遇到右括号则与栈顶元素匹配,并把栈顶元素出栈,不匹配则返回false,遍历结束后栈不为空返回false,若遍历结束后,栈为空,说明所有的左括号都与右括号匹配成功,则返回true。

这里为了不对三种括号分别判断,利用map存储左右括号的对应关系,使得代码好看一点。

class Solution {
    public boolean isValid(String s) {
        
        Stack<Character> stack = new Stack<>();
        Map<Character,Character> map= new HashMap<>();
        map.put(')','(');
        map.put('}','{');
        map.put(']','[');
        boolean flag = true;
        
        for(int i=0;i<s.length();i++)
        {
            char c = s.charAt(i);
            if(c=='('||c=='{'||c=='[')
                stack.push(c);
            if(c==')'||c=='}'||c==']')
            {
                if(stack.empty()) return false;
                else if(!stack.peek().equals(map.get(c))) return false;
                else stack.pop();
            }
        }
        
        return stack.empty(); 
        
    }
}
原文地址:https://www.cnblogs.com/trymorel/p/12525465.html