【发布时间】:2020-04-28 14:17:43
【问题描述】:
因此,手头的任务是递归地从给定字符串中删除重复项。例如-
输入:aabccba
输出:abcba
我的代码非常适合这个输入和其他 6 个测试用例中的 4 个。在这两个中,一个是运行时错误,而另一个是说我的代码给出了错误的答案。谁能告诉我如何解决这个问题?
public static String removeCons(String s) {
if(s.length() == 1) return s;
String ans = "";
String rest = "";
if(s.charAt(0) == s.charAt(1)) {
ans += s.charAt(0);
rest = removeCons(s.substring(2));
}
else {
ans += s.charAt(0);
rest = removeCons(s.substring(1));
}
return ans+rest;
}
【问题讨论】:
-
"aabccba".replaceAll("(.)\\1+", "$1"); -
什么是运行时错误? “错误答案”是什么?
-
@Fubar 我正在在线平台上运行此代码,不幸的是,这就是所有结果。
-
@SthitaprajnaMishra 然后在本地运行它,这样您就可以使用各种输入自行测试它。