【发布时间】:2014-07-17 05:56:42
【问题描述】:
我的代码旨在获取两个字符串,并在忽略大小写的情况下查看它们是否是彼此的直接反射。例如,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
}
【问题讨论】:
-
这个函数有很多问题:(1)递归什么时候结束? (2) 函数什么时候返回false? (3) 错误使用子串? (4)第一和第二互换。请至少自行修复其中一些。