0
点赞
收藏
分享

微信扫一扫

算法刷题 -- 20. 有效的括号 <难度 ★☆☆>

云竹文斋 2022-02-18 阅读 48

1、力扣原题

https://leetcode-cn.com/problems/valid-parentheses/

  • 解题思路
    放到一个栈里面,出栈入栈操作
class Solution {
    public boolean isValid(String s) {
        if (s == null) {
            return false;
        }
        Stack<Character> stack = new Stack<Character>();
        int count = s.length();
        for (int i = 0; i < count; i++) {
            Character c = s.charAt(i);
            if (stack.isEmpty()) {
                stack.push(c);
            } else {

                Character lastC = stack.peek();

                if ((lastC == '(') && (c == ')')) {
                    stack.pop();
                } else if ((lastC == '[' && c == ']')) {
                    stack.pop();
                } else if ((lastC == '{' && c == '}')) {
                    stack.pop();
                } else {
                    stack.push(c);
                }
            }
        }
        return stack.isEmpty();

    }
}
举报

相关推荐

0 条评论