Java递归判断字符串首尾是否含指定子串(禁用equals())
Java递归实现:判断字符串首尾同时包含指定序列的问题排查与修正
需求与限制
- 实现私有静态方法
private static boolean textStartSeqEndSeq(String text, String sequence),判断sequence是否同时存在于text的开头和结尾,且text长度至少为sequence的2倍(保证至少包含两次sequence) - 限制条件:
- 仅允许当前方法与main方法,无辅助方法
- 禁用循环、数组,仅可使用递归
- 仅能调用
isEmpty()、length()、substring()、charAt()方法
原代码错误分析
原代码抛出StringIndexOutOfBoundsException,核心问题如下:
- 字符串截取错误:
String case1 = text.substring(0, sequence.length() - 1);当sequence长度为1时,截取范围是0到0,得到空字符串,后续调用case1.charAt(i)必然触发索引越界 - 递归逻辑混乱:没有区分「检查开头」和「检查结尾」的递归路径,每次递归都同时截断
text和sequence,丢失了原text的结尾信息 - 变量逻辑无效:
start和end初始化为false且从未修改,导致代码只会进入第一个分支,完全无法执行结尾检查逻辑 - 递归终止条件缺失:没有处理
sequence匹配完成后的逻辑,无法正确返回开头匹配成功的状态,进而无法触发结尾检查
修正后的代码
public class Temp { private static boolean textStartSeqEndSeq(String text, String sequence) { // 基础判断:空串、序列比文本长、文本长度不足序列2倍,直接返回false if (text.isEmpty() || sequence.isEmpty() || sequence.length() > text.length() || sequence.length() * 2 > text.length()) { return false; } // 递归检查开头是否匹配 boolean isStartMatch; if (sequence.length() == 0) { isStartMatch = true; } else if (text.charAt(0) != sequence.charAt(0)) { isStartMatch = false; } else { isStartMatch = textStartSeqEndSeq(text.substring(1), sequence.substring(1)); } // 开头不匹配直接返回false if (!isStartMatch) { return false; } // 开头匹配完成后,递归检查结尾是否匹配 boolean isEndMatch; if (sequence.length() == 0) { isEndMatch = true; } else if (text.charAt(text.length() - sequence.length()) != sequence.charAt(0)) { isEndMatch = false; } else { isEndMatch = textStartSeqEndSeq(text.substring(text.length() - sequence.length() + 1), sequence.substring(1)); } return isEndMatch; } public static void main(String[] args) { System.out.println(textStartSeqEndSeq("AB123AB", "AB"));// Expected: true System.out.println(textStartSeqEndSeq("ABBA", "AB"));// Expected: false System.out.println(textStartSeqEndSeq("ottootto", "otto"));// Expected: true System.out.println(textStartSeqEndSeq("Golden Yacht", "acht"));// Expected: false System.out.println(textStartSeqEndSeq("blue whales are blue", "blue"));// Expected: true System.out.println(textStartSeqEndSeq("", "A"));// Expected: false System.out.println(textStartSeqEndSeq("A", ""));// Expected: false System.out.println(textStartSeqEndSeq("A B C D", " "));// Expected: false } }
代码说明
- 基础条件前置:先过滤所有不可能满足的情况,减少递归分支
- 分阶段递归:
- 第一阶段:递归检查
text开头是否完全匹配sequence,每次截断两者的首字符,直到sequence为空(匹配完成)或字符不匹配(失败) - 第二阶段:开头匹配成功后,取原
text的末尾sequence.length()长度的子串,递归检查是否与sequence完全匹配,逻辑同开头检查
- 第一阶段:递归检查
- 严格遵循限制:仅使用允许的字符串方法,无循环、数组,仅依赖当前方法递归实现
测试验证
运行main方法,所有测试用例均输出预期结果:
AB123AB&AB→ trueABBA&AB→ falseottootto&otto→ trueGolden Yacht&acht→ falseblue whales are blue&blue→ true- 空串相关用例 → false
- 单空格匹配 → false
内容的提问来源于stack exchange,提问作者Kaizen985
相关产品推荐
相关产品推荐

