-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncodeDecode.java
More file actions
68 lines (56 loc) · 2.07 KB
/
EncodeDecode.java
File metadata and controls
68 lines (56 loc) · 2.07 KB
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
package String;
import java.util.List;
public class EncodeDecode {
public static void main(String[] args) {
List.of("aa", "aaabb", "", " qqqwwb bbbmmmm ")
.stream()
.map(String::trim)
.forEach(EncodeDecode::printEncodeDecode);
printEncodeDecode(null);
}
private static void printEncodeDecode(String str) {
System.out.println("original : " + str);
try {
String encodedString = encode(str);
String decodedString = (encodedString.equals(str)) ? str : decode(encodedString);
System.out.println("encoded : " + encodedString);
System.out.println("decoded : " + decodedString);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static String encode(String str) throws RuntimeException {
if (str == null || str.isEmpty())
throw new RuntimeException("no string to encode");
StringBuilder sb = new StringBuilder();
int counter = 1, n = str.length();
for (int i = 0; i < n; i++) {
char c = str.charAt(i);
while (i < n - 1 && c == str.charAt(i + 1)) {
counter++;
i++;
}
sb.append(c);
sb.append(counter);
counter = 1;
}
return sb.length() < n ? sb.toString() : str;
}
private static String decode(String str) throws RuntimeException {
if (str == null || str.isEmpty())
throw new RuntimeException("no string to decode");
StringBuilder sb = new StringBuilder();
int n = str.length();
for (int i = 0; i < n; i++) {
char c = str.charAt(i);
if (Character.isDigit(c) && i != 0) {
int counter = str.charAt(i) - '0';
while (counter > 0 && !Character.isDigit(str.charAt(i - 1))) {
sb.append(str.charAt(i - 1));
counter--;
}
}
}
return sb.length() == 0 ? str : sb.toString();
}
}