[LeetCode] Encode and Decode Strings

271. Encode and Decode Strings

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.

Machine 1 (sender) has the function:

1
2
3
4
string encode(vector<string> strs) {
// ... your code
return encoded_string;
}

Machine 2 (receiver) has the function:

1
2
3
4
vector<string> decode(string s) {
//... your code
return strs;
}

So Machine 1 does:

string encoded_string = encode(strs);
and Machine 2 does:

vector<string> strs2 = decode(encoded_string);
strs2 in Machine 2 should be the same as strs in Machine 1.

Implement the encode and decode methods.

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
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.LinkedList;
import java.util.List;

public class Codec {
final private String SYMBOL = ".";
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for(String str : strs) {
sb.append(encodeBase64(str));
sb.append(SYMBOL);
}
return sb.toString();
}

// Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> res = new LinkedList<>();
int index = 0, prev = 0;
while(true) {
index = s.indexOf(SYMBOL, index);
if(index == -1)
break;
String subString = s.substring(prev, index);
res.add(decodeBase64(subString));
prev = ++index;
}

return res;
}

private String encodeBase64(String str) {
String res = "";
try {
byte[] targetBytes = str.getBytes("UTF-8");
Base64.Encoder encoder = Base64.getEncoder();

byte[] encodedBytes = encoder.encode(targetBytes);
res = encoder.encodeToString(targetBytes);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} finally {
return res;
}
}

private String decodeBase64(String str) {
Base64.Decoder decoder = Base64.getDecoder();

byte[] targetBytes = decoder.decode(str);

String res = "";
try {
res = new String(targetBytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} finally {
return res;
}
}
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/16/PS/LeetCode/encode-and-decode-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.