Skip to content

Commit 8b0b142

Browse files
committed
feat : encode-and-decode-strings
1 parent 802470e commit 8b0b142

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public String encode(List<String> strs) {
3+
StringBuilder res = new StringBuilder();
4+
for (String s : strs) {
5+
res.append(s.length()).append('|').append(s);
6+
}
7+
return res.toString();
8+
}
9+
10+
11+
/*
12+
* number + | + string
13+
* read number until |
14+
* move pointer, read substring
15+
*
16+
* tc : O(n) when n is the length of encoded string
17+
* sc : O(1)
18+
* */
19+
public List<String> decode(String str) {
20+
List<String> res = new ArrayList<>();
21+
int start = 0;
22+
while (start < str.length()) {
23+
int cur = start;
24+
//read until |
25+
while (str.charAt(cur) != '|') {
26+
cur++;
27+
}
28+
int length = Integer.parseInt(str.substring(start, cur));
29+
start = cur + 1;
30+
cur = start + length;
31+
res.add(str.substring(start, cur));
32+
start = cur;
33+
}
34+
return res;
35+
}
36+
}

0 commit comments

Comments
 (0)