首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >递归函数:检查Java中的回文

递归函数:检查Java中的回文
EN

Stack Overflow用户
提问于 2013-03-31 03:32:43
回答 6查看 18.6K关注 0票数 4

我有一个检查字符串是否为回文的类。我有两个问题。

1)这是检查回文的最有效的方法吗? 2)这可以递归实现吗?

代码语言:javascript
复制
public class Words {

    public static boolean isPalindrome(String word) {
    String pal = null;
    word = word.replace(" ", "");
    pal = new StringBuffer(word).reverse().toString();
    if (word.compareTo(pal) == 0) {
        return true;
    } else {
        return false;
    }

    }

}

有一个测试类来测试这个...怀疑它是必要的,但无论如何,如果有人愿意尝试一下,能够帮助我解决上面两个问题中的任何一个……

代码语言:javascript
复制
public class testWords {

    public static void main(String[] args) {
    if (Words.isPalindrome("a") == true) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }
    if (Words.isPalindrome("cat") == true) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }
    if (Words.isPalindrome("w o    w") == true) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }
    if (Words.isPalindrome("   a  ") == true) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }
    if (Words.isPalindrome("mom!") == true) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }

    }

}

提前感谢您的帮助和/或输入:)

EN

Stack Overflow用户

发布于 2013-03-31 03:42:25

实际上,只需检查中间字符以确认它是一个回文字符就足够了,这意味着您可以将其简化为如下所示:

代码语言:javascript
复制
// Length of my string.
int length = myString.length();

// Loop over first half of string and match with opposite character.
for (int i = 0; i <= length / 2; i++) {
    // If we find one that doesn't match then return false.
    if (myString.charAt(i) != myString.charAt(length - 1 - i)) return false;
}

// They all match, so we have found a palindrome!
return true;

递归解决方案是非常有可能的,但是它不会给你带来任何性能上的好处(而且可能不是那么好读)。

票数 5
EN
查看全部 6 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15722624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档