美文网首页
20. Valid Parentheses

20. Valid Parentheses

作者: becauseyou_90cd | 来源:发表于2018-08-01 23:56 被阅读0次

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<Character> stack = new Stack<Character>();
    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

      本文链接:https://www.haomeiwen.com/subject/kkjlvftx.html