LeetCode.678 Valid Parenthesis String

题目

Given a string containing only three types of characters: ‘(’, ‘)’ and ‘*’, write a function to check whether this string is valid. We define the validity of a string by these rules:

Any left parenthesis ‘(’ must have a corresponding right parenthesis ‘)’.
Any right parenthesis ‘)’ must have a corresponding left parenthesis ‘(’.
Left parenthesis ‘(’ must go before the corresponding right parenthesis ‘)’.
‘*’ could be treated as a single right parenthesis ‘)’ or a single left parenthesis ‘(’ or an empty string.
An empty string is also valid.

  • Example 1:
    • Input: “()”
    • Output: True
  • Example 2:
    • Input: “(*)”
    • Output: True
  • Example 3:
    • Input: “(*))”
    • Output: True
  • Note:
    The string size will be in the range [1, 100].

解答

class Solution {
    public boolean checkValidString(String s) {
        // 思路:左右括号匹配,*可以作为任何单独的:左括号、右括号、空符号,采用两个栈来记录左括号、星的位置
        if(s==null||s.length()==0){
            return true;
        }
        // 定义2个栈来存储对应下标
        Stack<Integer>leftStack=new Stack<>();
        Stack<Integer> starStack=new Stack<>();
        
        char[] chs=s.toCharArray();
        for(int i=0;i<chs.length;i++){
           char ch=chs[i];
            if(ch=='('){
                leftStack.push(i);
            }else if(ch=='*'){
                starStack.push(i);
            }else{
                // 判断左括号是否在星括号的右侧
                if(leftStack.isEmpty()&&starStack.isEmpty()){
                    return false;
                }else if(!leftStack.isEmpty()){
                    leftStack.pop();
                }else if(!starStack.isEmpty()){
                    starStack.pop();
                }
            }
        }
        
        // 判断leftStack是否为空,若不为空则校验两个栈的栈顶位置是否存在左括号在*括号的右边的情况,若存在则返回false
        while(!leftStack.isEmpty()){
            if(!starStack.isEmpty()){
                if(leftStack.peek()>starStack.peek()){
                    return false;
                }else{
                    leftStack.pop();
                    starStack.pop();
                }
            }else{
                return false;
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值