zoukankan      html  css  js  c++  java
  • 【数据结构】算法 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

  • 相关阅读:
    python 慕名函数
    python 不定长参数
    python 关键字参数
    python 传递参数
    python 函数的返回值
    python 函数的参数
    python 最简单的函数(无参无返回值)
    python 迭代器
    python 迭代器案例
    在 android 上运行 python 的方法
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14605290.html
Copyright © 2011-2022 走看看