1. 程式人生 > >20. Valid Parentheses 有效的括號

20. Valid Parentheses 有效的括號

題目


 

 


程式碼部分一(8ms 86.26%)

class Solution {
    public boolean isValid(String s) {
        Stack<Character> st = new Stack<Character>();
        
        char[] ch = s.toCharArray();
        if(ch.length == 0) return true;
        for(int i = 0; i < ch.length; i++){
            if(st.isEmpty())
                st.push(ch[i]);
            else if (st.peek() == '(' && ch[i] == ')' ||
                     st.peek() == '[' && ch[i] == ']' ||
                     st.peek() == '{' && ch[i] == '}')
                st.pop();
            else 
                st.push(ch[i]);
        }
        
        return st.isEmpty();
    }
}

 

 

程式碼部分二(7ms 90.26%)

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for(char c :s.toCharArray()){
            if(c=='('){
                stack.push(')');
            } else if(c=='['){
                stack.push(']');
            }else if(c=='{'){
                stack.push('}');
            }else if(stack.isEmpty()||stack.pop()!=c){
                return false;
            }
        }
        return stack.isEmpty();
    }
}

 

程式碼部分三(5ms 99.99%)

class Solution {
    public boolean isValid(String s) {
        char[] ch = s.toCharArray();
        int count = 0;
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            switch (c){
                case '(':
                case '[':
                case '{':ch[count++] = c; break;
                case ')':if(count == 0) return false;
                char c1 = ch[--count]; if(c1 != '(') return false;break;
                case ']':if(count == 0) return false;
                char c2 = ch[--count]; if(c2 != '[') return false; break;
                case '}':if(count == 0) return false;
                char c3 = ch[--count]; if(c3 != '{') return false; break;
            }
        }
        if(count != 0) return false;
        
        return true;
    }
    
}