力扣:2124. 检查是否所有 A 都在 B 之前

该博客探讨了一种字符串处理的方法,通过以特定字符B分割字符串并检查子串,来判断字符串是否包含特定子串A。提供了两种解决方案,一种是直接检查是否存在'ba'子串,另一种是使用字符串分割后再逐个检查。此问题适用于字符串分析和条件判断场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:字符串按B进行分割,去掉第一个分割的字符串,开始循环,如果字符串中包含了A,返回false,否则返回true;



/**
 * @author xnl
 * @Description:
 * @date: 2022/6/5   22:52
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String str = "aaabbb";
        System.out.println(solution.checkString(str));
    }

    public boolean checkString(String s) {
        if (s == null){
            return false;
        }
        if (!s.contains("a")){
            return true;
        }
        String[] split = s.split("b");
        for (int i = 1; i < split.length; i++){
            if (split[i].contains("a")){
                return false;
            }
        }
        return true;
    }
}

看了一下官方的第二个解答,真的是自己相想多了,不会仔细分析题,其实题目给出了只存在AB的两个字符组成的字符串,所以只需要判断是否存在ba这种字符串就行了。

public boolean checkString2(String s) {
        return !s.contains("ba");
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值