每日一题10

27 篇文章 0 订阅

力扣题:icon-default.png?t=LBL2https://leetcode-cn.com/problems/valid-parenthesis-string/

class Solution {
    public boolean checkValidString(String s) {
        int cnt1 = 0,cnt2 = 0,cnt3 = 0;
        int cnt4;
        for (int i = 0;i < s.length();i++){
            if (s.charAt(i)=='('){
                cnt1++;
            }

            if (s.charAt(i)==')'){
                cnt2++;
            }

            if (s.charAt(i)=='*'){
                cnt3++;
            }
        }

        if (cnt1 == cnt2){
            return true;
        }else if(cnt1 > cnt2){
            cnt4 = cnt1 - cnt2;
            if(cnt3 >= cnt4){
                return true;
            }
        }else {
            cnt4 = cnt2 - cnt1;
            if(cnt3 >= cnt4){
                return true;
            }
        }
        return false;
    }
}

 这是我自己本来的思路,但我只考虑到了左右括号数量上的问题,但忘记考虑了左括号要在右括号的左边这个问题,所以这个问题就没有得到解决,然后我就在题解里找到一个和我的思路有点相似的而且正确的方法学习了一下。

正确的代码如下

class Solution {
    //从0开始遍历,有一个右括号,就必须有一个左括号或者星号和它匹配,否则返回false。 
    //从结尾开始遍历,有一个左括号,就必须有一个右括号或者星号和它匹配,否则返回false。

    public boolean checkValidString(String s) {
		int left = 0;
		int right = 0;
		int star = 0;
        //从0开始遍历
		for(int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if(c == '(') {
				left++;
			}else if(c == ')') {
				right++;
			}else {
				star++;
			}
			if(right > 0) {
				if(left > 0) {
					left--;
					right--;
				}else if(star > 0) {
					star--;
					right--;
				}else {
					return false;
				}
			}
		}
		left = 0;
		right = 0;
		star = 0;
        //从结尾开始遍历
		for(int i = s.length() - 1; i >= 0; i--) {
			char c = s.charAt(i);
			if(c == '(') {
				left++;
			}else if(c == ')') {
				right++;
			}else {
				star++;
			}
			if(left > 0) {
				if(right > 0) {
					left--;
					right--;
				}else if(star > 0) {
					star--;
					left--;
				}else {
					return false;
				}
			}
		}
		return true;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值