You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodingBat String-2 endOther题目:其他测试用例报错求助

CodingBat String-2 endOther 问题排查

问题背景

题目要求:若字符串a出现在字符串b的末尾,或字符串b出现在字符串a的末尾,则返回true(忽略大小写)。
编写的代码如下:

public boolean endOther(String a, String b) {
      a = a.trim();
      a = a.toLowerCase();
      b = b.trim();
      b = b.toLowerCase();

      if (a.indexOf(b) == -1 && b.indexOf(a) == -1)
      return false;
      else if (a.indexOf(b) == a.length()-b.length()) 
      return true;
      else if (b.indexOf(a) == b.length()-a.length())
      return true;
      else
      return false;
    }

代码仅在「其他测试用例」中失败。

错误原因

你额外执行了trim()操作,题目并没有要求忽略首尾空格。比如测试用例a="Hi "、b="hi",你的代码会把a处理成"hi",错误返回true,但原字符串a的末尾是空格,b并没有出现在a的末尾,实际应该返回false。这就是导致测试用例失败的核心原因。

另外,你的判断逻辑可以简化,没必要先检查子串是否存在,直接验证结尾匹配即可。

修正后的代码

方案1:使用endsWith()方法(简洁高效)

public boolean endOther(String a, String b) {
    String lowerA = a.toLowerCase();
    String lowerB = b.toLowerCase();
    return lowerA.endsWith(lowerB) || lowerB.endsWith(lowerA);
}

方案2:手动截取结尾子串判断

如果不想使用endsWith(),可以手动截取对应长度的子串进行比较:

public boolean endOther(String a, String b) {
    String lowerA = a.toLowerCase();
    String lowerB = b.toLowerCase();
    
    int lenA = lowerA.length();
    int lenB = lowerB.length();
    
    if (lenA >= lenB) {
        return lowerA.substring(lenA - lenB).equals(lowerB);
    } else {
        return lowerB.substring(lenB - lenA).equals(lowerA);
    }
}

内容的提问来源于stack exchange,提问作者notzuriel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 09:26:15