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

20. Valid Parentheses

时间:2015-04-17 13:33:47      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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.

链接:http://leetcode.com/problems/valid-parentheses/

题解: 一道基本的使用stack的题目。 Time Complexity - O(n), Space Complexity - O(n)

public class Solution {
    public boolean isValid(String s) {
        if(s == null || s.length() == 0)
            return true;
        Stack<Character> stack = new Stack<Character>();
        
        for(int i = 0; i < s.length(); i ++){
            int left = s.charAt(i);
            if(left == ‘(‘ || left == ‘[‘ || left == ‘{‘) 
                stack.push(s.charAt(i));
            else {
                if(stack.isEmpty())
                    return false;
                char right = stack.pop(); 
                if(left == ‘]‘ && right != ‘[‘)
                    return false;
                else if(left == ‘}‘ && right != ‘{‘)
                    return false;
                else if (left == ‘)‘ && right != ‘(‘)
                    return false;
            }
        }
        
        if(!stack.isEmpty())
            return false;
        return true;
    }
}

 

20. Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/4434546.html

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