-
Notifications
You must be signed in to change notification settings - Fork 4
/
ConsecutiveDuplicatesRemover.java
71 lines (62 loc) · 2.25 KB
/
ConsecutiveDuplicatesRemover.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package string.removeDuplicates;
import utils.FunStringAlgorithm;
/**
* Given a string, remove all consecutive duplicate characters from it
* such that the result string does not contain consecutive duplicates.
*
* E.g. Input: "abbbcc" Output: "abc"
*
* @author ruifengm
* @since 2018-May-5
*
* https://www.geeksforgeeks.org/remove-consecutive-duplicates-string/
*
*/
public class ConsecutiveDuplicatesRemover extends FunStringAlgorithm {
/**
* Recursive method.
* Let A(n) be the char array, check if A[n-1] == A[n-2].
* If yes, remove A[n-1] and recur with A(n-1);
* else, keep A[n-1] and recur with A(n-1).
*/
private static String recursiveRemoveConsecutiveDuplicates(String s, int idx) {
if (idx <= 0) return s;
if (s.charAt(idx) == s.charAt(idx-1))
return recursiveRemoveConsecutiveDuplicates(s.substring(0, idx) + s.substring(idx+1, s.length()), idx-1);
else return recursiveRemoveConsecutiveDuplicates(s, idx-1);
}
private static String recursiveRemoveConsecutiveDuplicatesDriver(String s) {
return recursiveRemoveConsecutiveDuplicates(s, s.length()-1);
}
/**
* Iterative method.
*/
private static String iterativeRemoveConsecutiveDuplicates(String s) {
int i = s.length() - 1;
while (i>0) {
if (s.charAt(i) == s.charAt(i-1)) s = s.substring(0, i) + s.substring(i+1, s.length());
i--;
}
return s;
}
public static void main(String[] args) {
//String testStr = "azxxzy";
//String testStr = "whyydooiihhaavveeddupplicattess";
//String testStr = "caaabbbaacdddd";
String testStr = "acaaabbbacdddd";
//String testStr = "aaaaa";
//String testStr = "aaaabbbbc";
//String testStr = "";
System.out.println("Welcome to the rabbit hole of consecutive duplicate characters!");
System.out.println("The test string is: \n" + testStr+ "\n");
try {
runStringFuncAndCalculateTime("[Recursive] After removing consecutive duplicates:\n",
(String s) -> recursiveRemoveConsecutiveDuplicatesDriver(s), testStr);
runStringFuncAndCalculateTime("[Iterative] After removing consecutive duplicates:\n",
(String s) -> iterativeRemoveConsecutiveDuplicates(s), testStr);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("All rabbits gone.");
}
}