Java [Like 20] Valid parentheses

Given a string s containing only '(', ')', '{', '}', '[', ']', determine whether the string is valid.

A valid string must satisfy:

Opening parentheses must be closed with closing parentheses of the same type.
Left parentheses must be closed in the correct order.

Source: LeetCode
Link: https://leetcode-cn.com/problems/valid-parentheses

 code show as below:

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack=new Stack<>();
        // 将字符串转为字符输出
        for (int i = 0; i < s.length(); i++) {
            char c=s.charAt(i);
            // 碰到左括号直接入栈
            if(c=='('||c=='['||c=='{'){
                stack.push(c);
            }else {
                //此时c是个右括号
                if(stack.isEmpty()){
                    // 右括号是第一个字符,没有相应的左括号匹配
                    return false;
                }
                // 弹出左括号
                char top=stack.pop();
                if(c==')'&&top!='('){
                    return false;
                }
                if(c==']'&&top!='['){
                    return false;
                }
                if(c=='}'&&top!='{'){
                    return false;
                }
            }
        }
        // 此时字符串已经扫描完毕,判断当前栈中是否为空
        //若为空,则true,否则false
        return stack.isEmpty();
    }
}

Achieving the result:

Guess you like

Origin blog.csdn.net/m0_62218217/article/details/122658003