forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGangBean.java
More file actions
52 lines (45 loc) ยท 1.84 KB
/
GangBean.java
File metadata and controls
52 lines (45 loc) ยท 1.84 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
import java.util.*;
public class Codec {
/**
1. complexity:
- time: O(N * L), where N is the length of strs, L is maximum length of each word in strs
- space: O(N * L)
*/
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
// ํ์ํ ์ ๋ณด: ์ ์ฒด ์๋ณธ ๋ฌธ์์ด, ๊ฐ ๋จ์ด์ ์์น์ ๊ธธ์ด
StringBuilder origin = new StringBuilder();
StringJoiner meta = new StringJoiner("/");
StringJoiner encoded = new StringJoiner(";");
int startIdx = 0;
for (String word: strs) { // O(N)
origin.append(word);
meta.add(String.format("(%d,%d)", startIdx, word.length()));
startIdx += word.length();
}
encoded.add(origin.toString()).add(meta.toString());
return encoded.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> ret = new ArrayList<>();
int delimeterIdx = s.lastIndexOf(";"); // O(N * L)
String origin = s.substring(0, delimeterIdx); // O(N * L)
String meta = s.substring(delimeterIdx+1); // O(N * L)
String[] wordInfos = meta.split("/");
for (String wordInfo: wordInfos) { // O(N)
delimeterIdx = wordInfo.indexOf(","); // O(1)
int length = Integer.parseInt(wordInfo.substring(delimeterIdx+1, wordInfo.length() - 1)); // O(1)
String word = "";
if (length > 0) {
int startIdx = Integer.parseInt(wordInfo.substring(1, delimeterIdx));
word = origin.substring(startIdx, startIdx + length);
}
ret.add(word);
}
return ret;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));