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

20. Valid Parentheses

时间:2017-07-14 13:32:26      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:bre   str   log   push   case   and   contain   出栈   bool   

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.


括号匹配,遍历string,碰到左括号把左括号入栈,碰到右括号出栈,判断出栈的字符和右括号是否匹配。

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
                case ‘(‘:
                case ‘{‘:
                case ‘[‘:
                    stack.push(s.charAt(i));
                    break;
                case ‘)‘:
                    if (stack.empty() || stack.pop() != ‘(‘) {
                        return false;
                    }
                    break;
                case ‘}‘:
                    if (stack.empty() || stack.pop() != ‘{‘) {
                        return false;
                    }
                    break;
                case ‘]‘:
                    if (stack.empty() || stack.pop() != ‘[‘) {
                        return false;
                    }
                    break;
            }
        }
        if (stack.empty()) {
            return true;
        } else {
            return false;
        }
    }
}

 

20. Valid Parentheses

标签:bre   str   log   push   case   and   contain   出栈   bool   

原文地址:http://www.cnblogs.com/yuchenkit/p/7169505.html

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