java - 递归和字符串相等函数的问题
问题描述
' 该代码假设在 str 的子字符串中查找目标。它将 str 的子字符串与目标进行比较。它从第一个子字符串开始比较(由从 0 索引到 str 的 target.length-1 索引的字符组成)。如果 substring 不等于 target 它从 str 中删除第一个字符并再次将其返回给函数。如果 str 长度小于目标长度,则返回 false。'
'例如,如果 str = "superman" & target = "man"。与目标“man”相比,第一个子字符串是“sup”。这是错误的,因此“s”被删除。与“man”相比,下一个子字符串是“upe”,再次为假,因此“u”被删除。下一个带有“man”和“p”的“per”被删除。
'直到子字符串是“man”与目标“man”相比。在这里,它应该返回 true,但它没有,而是继续删除“m”并继续'
'很可能问题出在第 7 行'
public static boolean contains(String str, String target) {
if(str == null || target == null) { //null check
return false;
}
if(str.length() < target.length()) { // when string has less size than target, naturally its false
return false;
} else if(target.equals(str.substring(0,target.length()-1))) { //this is where the problem is
//more specifically, it isn't comparing the strings.
//Here if str and target are equal they should return true, but when the target is equal to str, it doesnt return true, instead treats it is if target is not equal to str.
return true;
} else {
return contains(str.substring(1),target);
}
}
解决方案
你是对的,问题在第 7 行,你不必减去 1 来定位。
方法:
public static boolean mycontains(String str, String target) {
if(str == null || target == null) {
return false;
}
if(str.length() < target.length()) {
return false;
} else if(target.equals(str.substring(0,target.length()))) {
return true;
} else {
return mycontains(str.substring(1),target);
}
}
推荐阅读
- javascript - 同一事件的不同动画
- virtualbox - 在“在 virtualbox guest NixOS 中添加共享文件夹”中结合两个 nix 表达式
- .net-core-2.0 - 在 .NET Core 中将 HTML 转换为图像
- extjs - 如何填充视口直到所有组件都是最小尺寸,然后添加滚动条?
- javascript - 使用javascript存储在关联数组中的多个用户表单输入
- python - 如何在没有导入的情况下获取python模块中定义的所有变量?
- ios - 接收方如何通知发送方接受和拒绝的动作?
- office-js - Excel Online 365 Javascript API 加载项会话超时
- python-2.7 - 使用带有原始 excel 数据的 python xlswriter 将宏添加到 excel
- firebase - 在 webpack vue 项目中添加 firebase 配置变量的位置