码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode20- Valid Parentheses- easy

时间:2017-12-02 11:31:01      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:cte   not   empty   ++   new   col   min   pre   经历   

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();
    }
}

 

leetcode20- Valid Parentheses- easy

标签:cte   not   empty   ++   new   col   min   pre   经历   

原文地址:http://www.cnblogs.com/jasminemzy/p/7948228.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!