20. Valid Parentheses

https://leetcode.com/problems/valid-parentheses/description/
解题思路:
1.遇到配对的我们用stack来解决。

  1. 遇到多个配对的外面用switch-case来解决。

代码:
class Solution {
public boolean isValid(String s) {

    if(s == null || s.length() == 0) return true;
    int len = s.length();
    if(len % 2 != 0) return false;
    Stack stack = new Stack();
    for(int i = 0; i < len; 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;
        }
    }
    return stack.empty();
}

}

你可能感兴趣的:(20. Valid Parentheses)