我正在尝试编写一个方法来检查给定的单词是否为回文,但到目前为止它还不起作用。我怀疑错误存在于if-语句中,并且您不使用==而是equals来比较诸如字符串之类的对象,对吗?然而,Java不允许我写:if (firstHalf.charAt(i).equals(secondHalf.charAt(j))),那么我能做些什么来使它工作呢?代码中还有其他错误吗?
public static boolean isPalindrome(String string) {
String firstHalf = string.substring(0, string.length() / 2);
String secondHalf = string.substring(string.length() / 2, string.length());
for (int i = 0; i <= firstHalf.length(); i++) {
for (int j = secondHalf.length(); j <= 0; j--) {
if (firstHalf.charAt(i) == secondHalf.charAt(j)) {
return true;
}
}
}
return false;
}发布于 2021-05-02 22:02:37
你的性格测试是倒退的。所有的比较都必须相等,字符串才能成为回文。
此外,拆分String也是不必要的。您可以在逻辑上将String拆分为两个索引。
试试这段代码。
public static boolean isPalindrome(String string) {
int frontIndex = 0;
int backIndex = string.length() - 1;
while (frontIndex < backIndex) {
if (string.charAt(frontIndex++) != string.charAt(backIndex--)) {
return false;
}
}
return true;
}https://stackoverflow.com/questions/67355263
复制相似问题