算法与数据结构——字符串括号类问题(Java)

有效的括号

image-20220711161732643

先解决怎么判断一个完整的括号字符串

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack=new Stack<>();
        for(char c:s.toCharArray()){
            if(c=='('){
                stack.push(')');
            }else if(c=='{'){
                stack.push('}');
            }else if(c=='['){
                stack.push(']');
            }else if(stack.isEmpty()||c!=stack.pop()){//注意这里两个判断条件的顺序不能调转  不然会导致在判断最后一个括号的时候判断完之后栈变成空的 因此直接返回false
                return false;
            }
        }
        return stack.isEmpty();
    }
}
  1. String.replace()
class Solution {
    public boolean isValid(String s) {
        int length = s.length() / 2;
		for (int i = 0; i < length; i++) {
			s = s.replace("()", "").replace("{}", "").replace("[]", "");
		}
		return s.length() == 0;
    }
}
  1. 用变量记录(这种方法也适用于多种括号的情况,多用几个变量来记录就行了)

    两个标准:

    • 一旦出现count小于0的情况就返回false
    • 遍历结束后count不等于0就返回false

    看至少需要添加几个括号的问题

    • count一旦小于0,res++,count变回0
    • 遍历完之后count剩下多少res就加多少
public int needNum(String str){
    int count=0;
    int res=0;
    for(int i=0;i<str.length();i++){
        if(str.charAt(i)=='('){
            count++;
        }else{//遇到了')'
            if(count==0){//说明前面少了'('
                res++;
            }else{
                count--;
            }
        }
    }
    return count+res;
}

括号的深度

image-20220712153126786

类似判断有效的括号

用一个变量count记录,遇到左括号++,遇到右括号–,记录count的最大值即可

public int getMax(String str){
    int count=0;
    int res=0;
    for(int i=0;i<str.length();i++){
        if(str.charAt(i)=='('{
            count++;
        }else{
            count--;
        }
        res=Math.max(res,count);
    }
    return res;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值