zoukankan      html  css  js  c++  java
  • leetcode——20. 有效的括号

    简单题:

    用栈实现:

    class Solution:
        def isValid(self, s: str) -> bool:
            if s=='':
                return True
            if len(s)==1:
                return False
            stack=[]
            i=0
            while i<len(s):
                if s[i] in '({[':
                    stack.append(s[i])
                    i+=1
                    if i==len(s):
                        return False
                else:
                    if stack==[]:
                        return False
                    if (s[i]==')' and stack.pop()=='(' )or (s[i]=='}' and stack.pop()=='{') or (s[i]==']' and stack.pop()=='['):
                        i+=1
                    else:
                        return False
            if stack!=[]:
                return False
            return True
    执行用时 :44 ms, 在所有 python3 提交中击败了84.49%的用户
    内存消耗 :13.8 MB, 在所有 python3 提交中击败了5.51%的用户
     
                                            ——2019.10.17
     

    public boolean isValid(String s) {
            char[] c = s.toCharArray();
            Stack<Character> stack = new Stack<>();
            if(s.equals("")){
                return true;
            }
            int len = s.length();
            for(int i = 0;i<len;i++){
                if(c[i] == '(' || c[i] == '[' || c[i] == '{'){
                    stack.push(c[i]);
                }else{
                    if(stack.isEmpty()){
                        return false;
                    }
                    char c2 = stack.pop();
                    if((c[i] == ')' && c2 == '(') || (c[i] == ']' && c2 == '[') || (c[i] == '}' && c2 == '{') ){
                        continue;
                    }else{
                        return false;
                    }
                }
            }
            if(!stack.isEmpty()){
                return false;
            }
            return true;
        }

    ——2020.7.14

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    leetcode——91.解码方法
    leetcode——64.最小路径和
    Layui上传图片2.0版
    LINQ中判断日期时间段
    Http基础
    Js中数组,字符串的常用方法
    C#数组,ArrayList,List区别
    08-01 通过线性回归了解算法流程
    08-00 课程习得
    C-02 推荐系统
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11690893.html
Copyright © 2011-2022 走看看