zoukankan      html  css  js  c++  java
  • leetcode20- Valid Parentheses- easy

    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.

    数据结构:用stack。看到左括号推入对应的右括号。看到右括号检查1.stack是不是空的弹不出来了 2.stack弹出来的是不是自己。看到其他符号肯定错。最后都遍历一遍了确认stack是不是空了,空了就说明全匹配了可以点头,否则说明有些没配上还是不行。

    实现:

    class Solution {
        public boolean isValid(String s) {
            Stack<Character> stack = new Stack<>();
            char[] chars = s.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                char c = chars[i];
                if (c == '(') {
                    stack.push(')');
                } else if (c == '{') {
                    stack.push('}');
                } else if (c == '[') {
                    stack.push(']');
                } else if (c == ')' || c == '}' || c == ']') {
                    if (stack.isEmpty() || stack.pop() != c) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
            // 千万小心不是经历完上面的for就是可以返回true了,一定要全匹配,stack空了才行,如果还剩下左括号没配上就还是错。
            return stack.isEmpty();
        }
    }
  • 相关阅读:
    一百多套开发视频教程的下载地址
    魅族MX3问题集锦
    Entity Framework 5问题集锦
    【PHP Manager for IIS】让IIS支持PHP
    MySQL安装
    phpMyAdmin安装
    犯了一个愚蠢的序列化错误
    最佳策略
    .net非托管资源
    .net内存何时回收?
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7948228.html
Copyright © 2011-2022 走看看