[leetcode] 678. Valid Parenthesis String

本文探讨了如何通过栈和双指针策略检查包含'(', ')' 和 '*' 的字符串是否有效。利用栈记录左括号和星号的位置,再通过比较栈顶元素确保所有左括号能被正确关闭。

Description

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:

  1. The string size will be in the range [1, 100].

分析

题目的意思是:验证一个字符串是否是合法字符串。

  • 这道题目我想到用了栈,但是没想到栈存放的是索引,在最后用来判断“*”能否消去s1里面的做括号,如果star的索引比s1的小,说明就不能当成右括号使用,直接返回false。

代码

class Solution {
public:
    bool checkValidString(string s) {
        stack<int> s1,star;
        for(int i=0;i<s.length();i++){
            if(s[i]=='('){
                s1.push(i);
            }else if(s[i]==')'){
                if(s1.empty()&&star.empty()){
                    return false;
                }
                if(s1.empty()&&!star.empty()){
                    star.pop();
                }else{
                   s1.pop(); 
                }
                
            }else{
                star.push(i);
            }
        }
        while(!s1.empty()&&!star.empty()){
            if(s1.top()>star.top()){
                return false;
            }
            star.pop();
            s1.pop();
        }
        return s1.empty();
    }
};

代码二(python)

  • 设两个变量l和h,l最少左括号的情况,h表示最多左括号的情况,其它情况在[l, h]之间。
  • 遍历字符串,遇到左括号时,l和h都自增1;当遇到右括号时,当l大于0时,l才自减1,否则保持为0(因为其它*情况可能会平衡掉),而h减1;
  • 当遇到星号时,当l大于0时,l才自减1(当作右括号),而h自增1(当作左括号)。如果h小于0,说明到此字符时前面的右括号太多,有*也无法平衡掉,返回false。
  • 当循环结束后,返回l是否为0。
class Solution:
    def checkValidString(self, s: str) -> bool:
        l=0
        h=0
        for ch in s:
            if(ch=='('):
                l+=1
                h+=1
            elif(ch==')'):
                if(l>0):
                    l-=1
                h-=1
            else:
                if(l>0):
                    l-=1
                h+=1
            if(h<0):
                return False
        return l==0

参考文献

[LeetCode] Valid Parenthesis String 验证括号字符串
[LeetCode] 678. Valid Parenthesis String 验证括号字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值