-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dedupe.java
106 lines (76 loc) · 2.53 KB
/
Dedupe.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Dedupe {
static String dedup(String inputStr, int chunkSize) {
Map<String, List<Integer>> mp = new HashMap<String, List<Integer>>();
int i=0;
while(i<inputStr.length()) {
String val=inputStr.substring(i, i+chunkSize);
if(mp.containsKey(val)) {
List<Integer> vals= mp.get(val);
vals.add(i);
mp.put(val, vals);
}
else {
List<Integer> vals= new ArrayList<>();
vals.add(i);
mp.put(val, vals);
}
i=i+chunkSize;
}
StringBuilder sb= new StringBuilder();
for (Map.Entry<String,List<Integer>> entry : mp.entrySet())
{
sb.append(entry.getKey());
List<Integer> vals= entry.getValue();
for(int k=0;k<vals.size();k++) {
if(k==vals.size()-1)
sb.append(vals.get(k)+"#");
else
sb.append(vals.get(k)+",");
}
}
return sb.substring(0, sb.length()-1);
}
static String redup(String deduplicatedStr, int chunkSize) {
int count=1;
for(int i=0;i<deduplicatedStr.length();i++) {
char c= deduplicatedStr.charAt(i);
if(c==',' || c=='#') {
count++;
}
}
int arraySize= chunkSize*count;
char[] ans= new char[arraySize];
String [] strings= deduplicatedStr.split("#");
for(String s: strings) {
String valueToInsert=s.substring(0,chunkSize);
String[] postionToInsert=s.substring(chunkSize).split(",");
for(int i=0;i<postionToInsert.length;i++) {
int start=Integer.valueOf(postionToInsert[i]);
for(int j=0;j<valueToInsert.length();j++) {
ans[start]=valueToInsert.charAt(j);
start++;
}
}
}
return new String(ans);
}
static String test(String inputStr, int chunkSize) {
String deduplicatedStr = dedup(inputStr, chunkSize);
if (deduplicatedStr.length() >= inputStr.length()) return "Deduplicated string length is greater than the input string length";
String originalStr = redup(deduplicatedStr, chunkSize);
return originalStr;
}
public static void main(String args[]) {
String inputStr="aabbaaac";
int chunkSize=2;
String dedupe= dedup(inputStr, chunkSize);
String reddupe = redup(dedupe, chunkSize);
System.out.println();
System.out.println(dedupe);
System.out.println(reddupe);
}
}