导航

Valid Parentheses

Posted on 2014-10-29 22:12  八竿子打不着  阅读(112)  评论(0)    收藏  举报

写了一个丑陋无比的解决方法,虽然知道怎么能够在让代码精简些,但是今晚太累人,改天再改。

public class Solution {
    public boolean isValid(String s) {
        if(s.length()%2==1){
            return false;
        }
        int i = 0;
        String res = "";
        boolean isok = true;
        while (i < s.length()) {
            char ar = s.charAt(i);
            if (ar == ']') {
                if (res.length() - 1 < 0 || res.charAt(res.length() - 1) != '[') {
                    isok = false;
                    break;
                } else {
                    res = res.substring(0, res.length() - 1);
                }
            } else if (ar == ')') {
                if (res.length() - 1 < 0 || res.charAt(res.length() - 1) != '(') {
                    isok = false;
                    break;
                } else {
                    res = res.substring(0, res.length() - 1);
                }
            } else if (ar == '}') {
                if (res.length() - 1 < 0 || res.charAt(res.length() - 1) != '{') {
                    isok = false;
                    break;
                } else {
                    res = res.substring(0, res.length() - 1);
                }
            } else {
                res = res + ar;
            }
            i++;
        }
        if(res.length()!=0){
            return false;
        }
        return isok;
        
    }
}