串出界误差与偶数长度字符串

问题描述 投票:0回答:1

我写我的版本是测试一个字是否是回文与否的方法。这似乎与奇数长度的字符串,但串出界异常错误的时候与偶数长度测试出现很好地工作。

任何帮助,将不胜感激!

public static boolean palindrome(String s, int start, int end) {

int length = s.length();


        if (length%2 != 0 && start != end) {
            if (s.charAt(start) == s.charAt(end)) {
                return palindrome(s,start+1,end-1);
            }
            else {
                return false;
            }
        }
        else if(length%2 == 0 && (start+1) != (end-1)) {
            if (s.charAt(start) == s.charAt(end)) {
                return palindrome(s,start+1,end-1);
            }
            else {
                return false;
            }
        }
        else if(length%2 != 0 && start == end) {
            return true;
        }
        else if(length%2 == 0 && start+1 == end-1) {
            if (s.charAt(start+1) == s.charAt(end-1)) {
                return true;
            }
            else {
                return false;
            }
        }
        else {
            return false;
        }

    }
java string recursion indexoutofboundsexception palindrome
1个回答
1
投票

我觉得你的代码是一个有点不必要复杂,您使用索引来你可以在Java子做什么。此外,你必须为偶数或奇数号码,你可以避开,通过只考虑他们在您的基本情况许多情况下。我试图让你的方法,降低了代码尽可能。我认为这是干净多了。在基础情况下,如果数是奇数它将在1结束,如果是即使将在2结束。

public boolean isPalindrome(String string)
{
    if (string.length() > 2) {
        if (string.charAt(0) == string.charAt(string.length() - 1)) {
            return this.isPalindrome(string.substring(1, string.length() - 1));
        } else {
            return false;
        }
    } else if (string.length() == 1) {
        return true;
    } else {
        if (string.charAt(0) == string.charAt(1)) {
            return true;
        } else {
            return false;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.