Valid Parenthesis 平衡符号

import java.util.Stack;

public 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{
                if(stack.isEmpty())
                    return false;

                char topChar = stack.pop();
                if(c == ')' && topChar != '(')
                    return false;
                if(c ==']' && topChar != '[')
                    return false;
                if(c == '}' && topChar != '{')
                    return false;
            }
        }
        return stack.isEmpty();
    }
}

本文来自博客园,作者:小恒2020,转载请注明原文链接:https://www.cnblogs.com/xiaoheng2020/p/12845290.html

原文地址:https://www.cnblogs.com/xiaoheng2020/p/12845290.html