【发布时间】:2019-09-23 15:13:27
【问题描述】:
这是我一直坚持的家庭作业。我给了一个 ArrayList,我需要返回一个所有字符都加倍的字符串。输入:abc,输出:aabbcc。我得到的输出是aa,然后它停止了。我已经通过循环多次执行此操作,但似乎无法通过递归获得它。
我尝试重新编辑我的代码并尝试使用计数器,但我得到一个空返回,或者我会得到一个堆栈溢出错误。我去了 Oracles 网站找出我可以使用的其他 String 方法,并尝试用其他方法更改我的代码,但仍然没有运气。
我的其他方法可以将 ArrayList 转换为字符串,但这是我遇到问题的最后一种方法。
public String dupEachChar2(String str) {
//str is going to be a string with abc in it.
String x = "";
int count = 0;
// I'm checking if there is only 1 char, if so just return it twice to 1 string.
if(str.length() == 1) {
return str + str;
} else if(count != str.length()) {
//Doubling part that I can not figure out.
x += str.substring(count, count+1) + str.substring(count, count+1);
count++;
dupEachChar2(str.substring(count));
}
return x;
}
【问题讨论】:
-
一定要用递归吗?
-
如果你不必使用递归,我会使用一行 regex
return str.replaceAll("(.)", "$1$1"); -
很遗憾,我愿意。我非常讨厌它。我仍然无法让它在我的脑海中点击。
标签: java string recursion char