zoukankan      html  css  js  c++  java
  • 有效的括号序列

    给定一个字符串所表示的括号序列,包含以下字符: '(', ')','{''}''[' and ']', 判定是否是有效的括号序列。

    样例

    括号必须依照 "()" 顺序表示, "()[]{}" 是有效的括号,但"([)]"则是无效的括号。

    挑战

    O(n)的时间,n为括号的个数

    public class Solution {
        /**
         * @param s A string
         * @return whether the string is a valid parentheses
         */
        public boolean isValidParentheses(String s) {
            // Write your code here
            Stack<Integer> stk = new Stack<Integer>();
            for(int i = 0;i < s.length();++i){
                int pos = "(){}[]".indexOf(s.substring(i,i+1));
                if(pos%2 == 1){
                    if(stk.isEmpty()||stk.pop()!= pos-1)
                       return false;
                }else {
                    stk.push(pos);
                }
            }
            return stk.isEmpty();
        }
    }
  • 相关阅读:
    113. Path Sum II
    112. Path Sum
    111. Minimum Depth of Binary Tree
    110. Balanced Binary Tree
    Create
    SetWindowPos
    INT_PTR数据类型
    SDK介绍
    COLORREF
    setfont()函数
  • 原文地址:https://www.cnblogs.com/wangnanabuaa/p/5122959.html
Copyright © 2011-2022 走看看