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

posted @ 2019-10-17 11:21  欣姐姐  阅读(183)  评论(0编辑  收藏  举报