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

被折叠的 条评论
为什么被折叠?



