我的代码用于获取两个字符串,并在忽略大小写时查看它们是否是彼此的直接反映。例如,isReverse(" abC"," cBA")应返回true,而isReverse(" abde"," aedb")返回false。
我无法确定它们是否是反射。为什么递归情况不起作用?我是递归编程的新手,这是一个非常大的挑战。
public static void main(String[] args) {
String first = "abadcd";
String second = "Dcdbua";
System.out.println(isReverse(first, second));
}
public static boolean isReverse(String first, String second) {
if (first.length() != second.length()) { // If string are not of equal length, impossible to be reverses
return false;
}
String check1 = "" + first.charAt(first.length() - 1);
String check2 = "" + second.charAt(0);
if (check1.equalsIgnoreCase(check2)) { // gets the 1st char of first and last char of 2nd to see if it matches
String temp1 = first.substring(1,first.length()-1); // shorten the string by escluding first char
String temp2 = second.substring(0, second.length()-2); // shorten the string by last char
isReverse(temp1, temp2);
}
return true; // reaches here after goes through
}
答案 0 :(得分:0)
这里有很多问题。
答案 1 :(得分:0)
您的代码中存在多个问题。
除了停止状态外,您需要在任何地方返回false
public static void main(String[] args)
{
String first = "abadcd";
String second = "Dcdbua";
String third = "dcdabA";
System.out.println("Should be false = " + isReverse(first, second));
System.out.println("Should be true = " + isReverse(first, third));
}
public static boolean isReverse(String first, String second)
{
System.out.println("1=" + first + " / 2=" + second);
if (first.length() != second.length())
{ // If string are not of equal length, impossible to be reverses
return false;
}
// Stopping condition
if (first.length() == 0 && second.length() == 0)
{
return true;
}
String check1 = "" + first.charAt(first.length() - 1);
String check2 = "" + second.charAt(0);
if (check1.equalsIgnoreCase(check2))
{ // gets the 1st char of first and last char of 2nd to see if it matches
String temp1 = first.substring(0, first.length() - 1); // shorten the string by escluding first char
String temp2 = second.substring(1, second.length()); // shorten the string by last char
return isReverse(temp1, temp2);
}
return false; // reaches here after goes through
}