forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathekgns33.java
More file actions
36 lines (34 loc) · 838 Bytes
/
ekgns33.java
File metadata and controls
36 lines (34 loc) · 838 Bytes
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
class Solution {
public String encode(List<String> strs) {
StringBuilder res = new StringBuilder();
for (String s : strs) {
res.append(s.length()).append('|').append(s);
}
return res.toString();
}
/*
* number + | + string
* read number until |
* move pointer, read substring
*
* tc : O(n) when n is the length of encoded string
* sc : O(1)
* */
public List<String> decode(String str) {
List<String> res = new ArrayList<>();
int start = 0;
while (start < str.length()) {
int cur = start;
//read until |
while (str.charAt(cur) != '|') {
cur++;
}
int length = Integer.parseInt(str.substring(start, cur));
start = cur + 1;
cur = start + length;
res.add(str.substring(start, cur));
start = cur;
}
return res;
}
}