• 20 Valid Parentheses


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

    The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

    判断一个括号字符串是否是有效

    public class Solution {  
      
        public boolean isValid(String s) {  
            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();  
        }  
    }  

    解题思路:判断括号匹配的合法性。使用一个栈来解决问题。遇到左括号入栈,遇到右括号,检查栈顶的左括号是否匹配,如果匹配,弹栈,如果不匹配,返回错误。如果栈为空,而遇到右括号,同样返回错误。遍历完后,栈如果不空,同样返回错误。

    class Solution:
        # @return a boolean
        def isValid(self, s):
            stack = []
            for i in range(len(s)):
                if s[i] == '(' or s[i] == '[' or s[i] == '{':
                    stack.append(s[i])
                if s[i] == ')':
                    if stack == [] or stack.pop() != '(':
                        return False
                if s[i] == ']':
                    if stack == [] or stack.pop() != '[':
                        return False
                if s[i] == '}':
                    if stack == [] or stack.pop() != '{':
                        return False
            if stack:
                return False
            else:
                return True
  • 相关阅读:
    sh_04_第1个函数改造
    sh_03_第1个函数
    sh_02_快速体验
    sh_01_九九乘法表
    11_测试模块
    sh_12_转义字符
    sh_11_九九乘法表
    sh_10_嵌套打印小星星
    Mariadb/Redis数据库
    部署django项目
  • 原文地址:https://www.cnblogs.com/zxqstrong/p/5280108.html
Copyright © 2020-2023  润新知