使用递归进行双字符串比较

Eog*_*oud 5 java

我在编程II课程中遇到一些问题并遇到了困难,想知道是否有人可以提供帮助?

该问题要求用户输入一个字符串,该程序用于反转输入字符串,然后将其反向与原始字符串进行比较,这必须以递归方式完成.

到目前为止,我有:

public class question1 
{
public static void main(String args[])  
{

String input = JOptionPane.showInputDialog(null, "Please enter a sentence to determine if it is a palindrome.");
String backwardsinput = Reverse(input);
System.out.println(backwardsinput);
boolean Palindrome = PalindromeCheck(backwardsinput, input);

    if (Palindrome == true)

        {
        JOptionPane.showMessageDialog(null,"That is a palindrome!");
        }

    if (Palindrome == false)

        {
        JOptionPane.showMessageDialog(null,"That is not a palindrome"); 
        }

}

public static String Reverse (String input)
{
    if (input.length() <= 1)
    return input;

    else
    {
        char x = input.charAt(input.length()-1);               
        return x+Reverse(input.substring(0,input.length()-1));
    }

}



public static boolean PalindromeCheck (String backwardsinput, String input)
{

     if(input.length() == 0 || input.length() == 1)
            return true;

        if(backwardsinput.charAt(0) == input.charAt(input.length()-1))
            return PalindromeCheck(backwardsinput.substring(1, backwardsinput.length()-1), input.substring(1, input.length()-1));

        else
        return false;

       }    
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,它告诉我一切都是回文,我一遍又一遍地看着它,无法弄清楚为什么!

aio*_*obe 6

你正在做两次工作(有点).

if(backwardsinput.charAt(0) == input.charAt(input.length()-1))
                                            ^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

应该

if (backwardsinput.charAt(0) == input.charAt(0))
                                             ^
Run Code Online (Sandbox Code Playgroud)

你几乎得到了它:-)


另外,另一种表达方式

if (cond)
    return something;
else
    return false;
Run Code Online (Sandbox Code Playgroud)

return cond && something;
Run Code Online (Sandbox Code Playgroud)

因此你的最后一行可以写成

return backwardsinput.charAt(0) == input.charAt(0) &&
       palindromeCheck(backwardsinput.substring(1, backwardsinput.length() - 1),
                                input.substring(1, input.length() - 1));
Run Code Online (Sandbox Code Playgroud)

相关问题/答案: