【数据结构】算法 Valid Parentheses 有效的括号

Valid Parentheses 有效的括号

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

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
Example 1:

Input: s = "()"
Output: true
Example 2:

Input: s = "()[]{}"
Output: true
Example 3:

Input: s = "(]"
Output: false
Example 4:

Input: s = "([)]"
Output: false
Example 5:

Input: s = "{[]}"
Output: true

思路

使用栈,扫描string,遇到左括号,就push,遇到相同类型的右括号就pop,如果遇到不匹配的括号,肯定是false

public boolean isValid(String s) {
         Stack<Character> st = new Stack<>();
        for (int i = 0; i < s.length(); i++){
            switch (s.charAt(i)){
                case '(':
                case '[':
                case '{': st.push(s.charAt(i));
                break;
                case ')':
                    if(st.isEmpty()||st.peek()!='('){
                        return false;
                    }
                    st.pop();
                    break;
                case ']':
                    if(st.isEmpty()||st.peek()!='['){
                        return false;
                    }
                    st.pop();
                    break;
                case '}':
                    if(st.isEmpty()||st.peek()!='{'){
                        return false;
                    }
                    st.pop();
                    break;
                default:
                    break;
            }

        }
        return st.isEmpty();
    }

Tag

stack

原文地址:https://www.cnblogs.com/dreamtaker/p/14605290.html