[lintcode] problem 659 – 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.

Please implement encode and decode

Example

No.1

Input: [“lint”,”code”,”love”,”you”]

Output: [“lint”,”code”,”love”,”you”]

Explanation:
One possible encode method is: “lint:;code:;love:;you”

No.2

Input: [“we”, “say”, “:”, “yes”]

Output: [“we”, “say”, “:”, “yes”]

Explanation:
One possible encode method is: “we:;say:;:::;yes”

Code

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
public String (List<String> strs) {
StringBuilder sb = new StringBuilder();

for (String str : strs) {
for (char ch : str.toCharArray()) {
if (ch == ':')
sb.append("::");
else
sb.append(ch);
}

sb.append(":;");
}

return sb.toString();
}

public List<String> decode(String str) {
List<String> result = new ArrayList<>();
StringBuilder sb = new StringBuilder();

for (int i = 0; i < str.length();) {
char ch = str.charAt(i);

if (ch == ':') {
result.add(sb.toString());

if (str.charAt(i + 1) != ';')
result.add(":");

sb.setLength(0);
i += 2;
}
else {
sb.append(ch);
i++;
}
}

return result;
}