-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncodeDecode.java
More file actions
60 lines (55 loc) · 2.08 KB
/
EncodeDecode.java
File metadata and controls
60 lines (55 loc) · 2.08 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
/*
* Design an algorithm to encode a list of strings
* to a string. The encoded string is then sent over
* the network and is decoded back to the original
* list of strings.
Please implement encode and decode
*/
import java.util.*;
public class EncodeDecode {
/*
* @param strs: a list of strings
* @return: encodes a list of strings to a single string.
*/
public static String encode(List<String> strs) {
// write your code here
StringBuilder encodedString = new StringBuilder();
for (String str : strs) {
encodedString.append(str.length()).append("#").append(str);
}
return encodedString.toString();
}
/*
* @param str: A string
* @return: decodes a single string to a list of strings
*/
public static List<String> decode(String str) {
// write your code here
List<String> decodedStrings = new ArrayList<>();
int i = 0;
while (i < str.length()) {
// Find position of delimiter '#'
int delimiterIndex = str.indexOf('#', i);
System.out.println("delimiterIndex: " + delimiterIndex);
// Extract the length of the string
int length = Integer.parseInt(str.substring(i, delimiterIndex));
System.out.println("length: " + length);
// Move i to the start of the string
i = delimiterIndex + 1;
System.out.println("i: " + i);
// Extract the string of the specified length and add it to the list
decodedStrings.add(str.substring(i, i + length));
System.out.println("DecodedString: " + decodedStrings);
// Move i past the curent string
i += length;
System.out.println("i: " + i);
}
return decodedStrings;
}
public static void main(String[] args) {
List<String> input1 = Arrays.asList("neet", "code", "love", "you");
String encoded1 = encode(input1);
System.out.println("Encoded: " + encoded1);
System.out.println("Decoded: " + decode(encoded1));
}
}