LeetCode:678 valid parenthesis String

problem

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.

solution

和LeetCode20题相比,有不相同的地方
这是第20题的进阶版,自己确实一点思路都没有,总觉得可以很巧妙的利用这个星号,却不知道怎么用╮(╯▽╰)╭

i:看了这么久,最理解的就是双栈的方案了
这里双栈的方案很巧,可以解决**“空间问题”:因为星号是可以取3种情况的,如果只局限于星号的前后就会出错,比如‘(****)’,或是这样((),你很难判断当你取到星号时,你将对星采取什么样的方式处理,所以当你用单个栈取到星号而只考虑其当时情况时,是很难分析的
解题方法就是用两个栈,一个stack ,一个stack_star,记录’(‘和星出现的位置,然后尽量去把’)‘消除完毕,
因为不管’(‘的位置在哪里,中间隔了几个星号,星号任意性都可以当做不存在而消掉一对括号,直到消除完’)’,剩下’(‘和星号最重要的是’(‘的位置一定要小于星号位置,因为对’('匹配的一定在它本身之后
注意空

python

class Solution:
    def checkValidString(self, s: str) -> bool:
        length=len(s)
        stack=[]
        stack_star=[]
        for i in range(length):
            if s[i]=='(':
                stack.append(i)
            elif s[i]=='*':
                stack_star.append(i)
            else:
                if not stack and  not stack_star:
                    return False
                if stack:
                    stack.pop()
                else:
                    stack_star.pop()
        if len(stack)>len(stack_star):
            return False
        i=len(stack)-1
        while(i>=0):
            if stack.pop()>stack_star.pop():
                return False
            i-=1
        return True

java

class Solution {
    public boolean checkValidString(String s) {
        int length = s.length();
        Stack<Integer> stack = new Stack<>();
        Stack<Integer> stack_star = new Stack<>();
        for (int i = 0; i < length; ++i) {
            if (s.charAt(i) == '(') {
                stack.push(i);
            } else if (s.charAt(i) == '*') {
                stack_star.push(i);
            } else {
                if (stack.isEmpty() && stack_star.isEmpty()) {
                    return false;
                }
                if (!stack.isEmpty()) {
                    stack.pop();
                } else {
                    stack_star.pop();
                }
            }

        }
        while (!stack.isEmpty() && !stack_star.isEmpty()) {
            if (stack.pop() > stack_star.pop()) {
                return false;
            }
        }
        if(stack.isEmpty()){
            return true;
        }
        return false;
    }
}

ii贪心算法
我们要设立左括号的最少个数和最多个数low,high,期间要对low进行维护,记住就是在能有左括号最多的情况下能够满足就可以成立(连有最多左括号都无法满足的话,,)在左括号最少的情况下左括号左还有剩余就不成立

  • 遍历s
  • 遇见’(’,则最少和最多各数都加1
    遇见’)’,最多剪掉1,最少进行维护:最少大于零的话,剪掉一,否则不变
    遇见’*’,最多加一,最少进行维护,最少大于零的话,剪掉一,否则不变
    如果最多小于0,则说明没有多的’(‘和当前’)'匹配
  • 循环完毕
    如果剩下最少的括号还有的话,证明有多余的’(’,(前面是进行了维护的,所以本来low是可以为负的,但是连low都没有消耗完毕╮(╯▽╰)╭)

python

class Solution:
    def checkValidString(self, s: str) -> bool:
        length=len(s)
        low=high=0
        for i in range(length):
            if s[i]=='(':
                low+=1
                high+=1
            elif s[i]==')':
                if low>0:
                    low-=1
                high-=1
            else:
                if low>0:
                    low-=1
                high+=1
            if high<0:
                return False
        return low==0

java

class Solution:
    def checkValidString(self, s: str) -> bool:
        length=len(s)
        low=high=0
        for i in range(length):
            if s[i]=='(':
                low+=1
                high+=1
            elif s[i]==')':
                if low>0:
                    low-=1
                high-=1
            else:
                if low>0:
                    low-=1
                high+=1
            if high<0:
                return False
        return low==0

iii:双向遍历:
分两种情况
对’(’,把星作’(’,把’(‘最大化,从左往右遍历,在遍历过程中,’)‘还有剩余,即left为负,不成立:用最多的左括号去和右括号匹配,如果右括号还有剩余,就是不成立的
如果left刚好为0,证明’(’,’)’,星三者能刚好抵消,为真
对’)’,把’*‘当作’)’,把’)‘最大化道理同上,从右往左遍历,在遍历过程中,’('还有剩余,即right为负,不成立,思想于上面同理
这种方式,个人感觉,有点把贪心算法的方法拆分成了两个方向

python

class Solution:
    def checkValidString(self, s: str) -> bool:
        length = len(s)
        left = right = 0
        for i in range(length):
            if s[i] == '(' or s[i] == '*':
                left += 1
            else:
                left -= 1
            if left < 0:
                return False
        if left == 0:
            return True
        for i in range(length):
            if s[length - 1 - i] == ')' or s[length - 1 - i] == '*':
                right += 1
            else:
                right -= 1
            if right < 0:
                return False
        return True

Java

class Solution {
    public boolean checkValidString(String s) {
        int left = 0, right = 0, length = s.length();
        char[] chars = s.toCharArray();
        for (int i = 0; i < length; ++i) {
            if (chars[i] == '(' || chars[i] == '*') {
                ++left;
            } else {
                left--;
                if (left < 0) {
                    return false;
                }
            }
        }
        if (left == 0) return true;
        for (int j = length - 1; j >= 0; --j) {
            if (chars[j] == ')' || chars[j] == '*') {
                ++right;
            } else {
                --right;
                if (right < 0) {
                    return false;
                }
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值