我试图写一个递归,其中一个词试图镜像自己(appleelppa)。我的思维过程是使用递归,将单词按反向顺序打印出来,然后在开头添加单词。然而,这在某种程度上是行不通的。这是我的密码
public static String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return str + reverse(str.substring(1)) + str.charAt(0);
}这是它的输出:小鳞翅目苹果
有什么帮助吗?
谢谢
发布于 2014-04-15 01:58:46
您的reverse例程几乎是正确的(但是您确实应该添加一个mirror例程,您的方法还是很混乱)。你想要这样的东西,
// Reverse the input String str.
private static String reverse(String str) {
// This just looked ugly.
if (str == null || str.length() <= 1) {
return str;
}
// this is how you recursively reverse the word.
return reverse(str.substring(1)) + str.charAt(0);
}
// mirror is trivial, the word and the reverse of the word.
public static String mirror(String str) {
return str + reverse(str);
}
public static void main(String[] args) {
String str = "apple";
System.out.println(mirror(str));
}输出(按要求)
appleelppa编辑
// mirror an input string iteratively.
public static String mirror(String str) {
// return str + reverse(str);
StringBuilder sb = new StringBuilder(str);
return str + sb.reverse().toString();
}发布于 2014-04-15 01:47:34
如果您只是编写一个递归函数来反转字符串,然后将其添加到原始字符串中,则会简单得多。
public class Reverse{
public static String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) {
System.out.println("appleelppa" + reverse("appleelppa"));
}
}是一种使用递归而不是迭代的方法。注意到,这是,而不是的首选方法。因为他很好奇,所以把它放在这里只是为了表明它是可以做到的。这是受到AdrianShum评论的启发。
public class Reverse{
public static String mirror(String str, boolean firstCall) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
if (firstCall)
return str + mirror(str.substring(1), false) + str.charAt(0);
else
return mirror(str.substring(1),false) + str.charAt(0);
}
public static void main(String[] args) {
System.out.println(mirror("appleelppa", true));
}
}发布于 2014-04-15 02:15:42
你得到的所有答案都给了你新的解决方案。我是来告诉你你的解决方案是90%正确的。
从以下位置删除str +:
return str + reverse(str.substring(1)) + str.charAt(0);使:
return reverse(str.substring(1)) + str.charAt(0);你原来的功能就像一种魅力;)
https://stackoverflow.com/questions/23073286
复制相似问题