首页 > 其他 > 详细

LeetCode -- Valid Parenthese

时间:2015-10-12 21:05:57      阅读:259      评论:0      收藏:0      [点我收藏+]

Question:

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.

 

Analysis:

问题描述:给出一个字符串,包含‘(‘‘)‘‘{‘‘}‘‘[‘ and ‘]‘确定它是否是有效地匹配括号。

思路:一看到括号匹配问题肯定想到用栈。遇到左括号就进栈;遇到右括号若栈顶元素与之匹配则POP出栈顶元素,若不匹配则返回false。

注意特殊情况:如"{}[]()", 或者“{[}]”, 或者“{{}}{{”等情况。

 

Answer:

public class Solution {
    public boolean isValid(String s) {
        char[] ch = s.toCharArray();
        int n = ch.length;
        if(ch.length == 0 || ch.length % 2 != 0)
            return false;
        if(ch[0] == ‘}‘ || ch[0] == ‘]‘ || ch[0] == ‘)‘)
            return false;
        Stack<Character> st = new Stack<Character>();
        st.add(ch[0]);
        int i = 1;
        while(!st.isEmpty() && i < n) {
            if(ch[i] == ‘{‘ || ch[i] == ‘[‘ || ch[i] == ‘(‘) {
                st.add(ch[i]);
                i++;
            } else {
                if(st.isEmpty())
                    return false;
                char c = st.pop();
                if(c == ‘{‘ && ch[i] != ‘}‘ || c == ‘[‘ && ch[i] != ‘]‘
                        || c == ‘(‘ && ch[i] != ‘)‘)
                    return false;
                i++;
                if(i < n && (ch[i] == ‘{‘ || ch[i] == ‘[‘ || ch[i] == ‘(‘)) {
                    st.add(ch[i]);
                    i++;
                } 
            }
        }
        System.out.println(i +" " +st.size());
        if(!st.isEmpty() || i < n - 1)
            return false;
        
        return true;
    }
    
}

 

LeetCode -- Valid Parenthese

原文:http://www.cnblogs.com/little-YTMM/p/4872737.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!