拆分和比较一个字符串(Java)

我已经测试了一段时间的不同方法,这就是我得到的。我只是不知道如何解决这个问题。


/** Return true iff s has an odd number of characters and

 *  the substring before the middle character equals the substring

 *  after it.

 * Examples: For s = "" return false

 * For s = "b" return true

 * For s = "xbx" return true

 * For s = "xxxx" return false

 * For s = "hellohello" return false

 * For s = "hello!hello" return true */

public static boolean isDoubled(String s) {

    // TODO 1. There is no need for a loop. Do not use a loop.

    // In all methods, use s1.equals(s2) and NOT s1 == s2 to test

    // equality of s1 and s2.

    int midLen = s.length() / 2;

    if (midLen == 0) return false;

    String[] parts = {s.substring(0, midLen - 1), s.substring(midLen + 1)};

    String part1 = parts[0];

    String part2 = parts[1];

    if ((s.length() % 2 == 0) && (part1.equals(part2))) {

        return true;

    }

    return false;

}


慕容3067478
浏览 245回答 3
3回答

HUWWW

您在使用substring函数时有错误:public static boolean isDoubled(String s) {    if (s.length() % 2 == 0)        return false;    if (s.length() == 1)        return true;    int mid = s.length() / 2;    return s.substring(0, mid).equals(s.substring(mid + 1));}

森林海

当您将两个索引(a,b)传递给子字符串方法时,该方法包括索引,但不包括索引b。从数学上讲,它是[a,b)。如果您考虑字符串“ hello!hello”,那么mid将是索引5。当您说-String[] parts = {s.substring(0, midLen - 1), s.substring(midLen + 1)};您得到的两个部分是s.substring(0, 4) //this gets you the string "hell"s.substring(6)    //this gets you the string "hello"显然,它们不匹配。导致错误的对等。您需要做一个小改动-String[] parts = {s.substring(0, midLen), s.substring(midLen + 1)};

ibeautiful

两个简单的错误:在你的if-statement你如果长度甚至,当你想,以确保它是不是连。(更改(s.length() %2===0)为!(s.length() %2 == 0)而且该substring功能不具有包容性,因此您想更改s.substring(0, mid-1)为s.substring(0, mid)(从docs中:“子字符串从指定的beginIndex开始,并扩展到索引endIndex-1处的字符。 ”)同样,您不需要将in的两个部分array放入变量中。您可以简单地将它们进行比较,例如: parts[0].equals(parts[1])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java