我需要使用递归方法从字符串中删除连续的重复项(例如,将“aabbcddeghhi”转换为“abcdefghi”。)到目前为止,我有这个。
如果我有a195b197199d201203205207h209Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 13
行被注释,我会得到一个带有数字的奇怪输出和这个例外:
a
如果我注释掉那一行,它就会打印出来:
package recursion;
public class recursion {
public static void main(String[] args){
removeDuplicates("aabbcddefghhi", 0, 1);
}
public static void removeDuplicates(String a, int b, int c){
if (a.length() <= 1){
System.out.print(a.charAt(b));
}
else if (a.charAt(b) == a.charAt(c)){
System.out.print(a.charAt(c));
b++;
c++;
//removeDuplicates(a,b,c);
}
else if (a.charAt(b) != a.charAt(c)){
System.out.print(a.charAt(b) + a.charAt(c));
b++;
c++;
removeDuplicates(a,b,c);
}
else{
System.out.print("");
b++;
c++;
removeDuplicates(a,b,c);
}
}
}
这是我的代码:
{{1}}
答案 0 :(得分:1)
此代码存在一些问题:
c
值,它始终等于b+1
,只需使用一个数字。以下是包含所有这些更改的结果代码:
public static void main(String[] args) {
removeDuplicates("a");
System.out.println();
removeDuplicates("aabbcdddefghhii");
System.out.println();
removeDuplicates("aabbcdefa");
}
public static void removeDuplicates(String a) {
removeDuplicatesHelper(a, 0);
}
public static void removeDuplicatesHelper(String a, int b) {
if (b == a.length() - 1) {
System.out.print(a.charAt(b));
} else if (a.charAt(b) == a.charAt(b+1)) {
b++;
removeDuplicatesHelper(a, b);
} else {
System.out.print(a.charAt(b));
b++;
removeDuplicatesHelper(a, b);
}
}
输出:
a
abcdefghi
abcdefa
答案 1 :(得分:0)
Biginteger
请致电:
public static String duplicates(String word, char curr) {
if (word.length() == 0) return "";
char next = word.charAt(0);
if (word.length() == 1) {
return curr == next ? "" : word;
}
if (curr != next) {
return next + duplicates(word.substring(1), next);
}
else {
return duplicates(word.substring(1), curr);
}
}