-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path659.strings-serialization.java
More file actions
57 lines (52 loc) · 1.58 KB
/
659.strings-serialization.java
File metadata and controls
57 lines (52 loc) · 1.58 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
public class Solution {
/*
* @param strs: a list of strings
* @return: encodes a list of strings to a single string.
*/
public String encode(List<String> strs) {
if (strs == null) {
return "";
}
// use ":;" to separate strings, use "::" to represent ":"
StringBuilder ans = new StringBuilder();
for (String str : strs) {
for (char c : str.toCharArray()) {
if (c == ':') { // ":" itself
ans.append("::");
} else { // ordinary character
ans.append(c);
}
}
ans.append(":;"); // ";" separator
}
return ans.toString();
}
/*
* @param str: A string
* @return: dcodes a single string to a list of strings
*/
public List<String> decode(String str) {
List<String> ans = new ArrayList<>();
if (str == null || str.length() == 0) {
return ans;
}
char[] sc = str.toCharArray();
int i = 0;
StringBuilder sb = new StringBuilder();
while (i < sc.length) {
if (sc[i] == ':') {
if (sc[i + 1] == ';') {
ans.add(sb.toString());
sb = new StringBuilder();
i += 2;
} else {
sb.append(":");
i += 2;
}
} else {
sb.append(sc[i++]);
}
}
return ans;
}
}