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

阅读 48

2022-02-18

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)

0 0 举报