Skip to content

Commit 3c3ba5b

Browse files
committed
encode and decode strings solution
1 parent 40601e8 commit 3c3ba5b

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
public class Codec {
2+
3+
// Encodes a list of strings to a single string.
4+
public String encode(List<String> strs) {
5+
StringBuilder sb = new StringBuilder();
6+
7+
for (String s : strs) {
8+
sb.append(s.length()).append('#').append(s);
9+
}
10+
11+
return sb.toString();
12+
}
13+
14+
// Decodes a single string to a list of strings.
15+
public List<String> decode(String s) {
16+
List<String> res = new ArrayList<>();
17+
int i = 0;
18+
19+
while (i < s.length()) {
20+
int j = i;
21+
22+
// find '#'
23+
while (s.charAt(j) != '#') {
24+
j++;
25+
}
26+
27+
int length = Integer.parseInt(s.substring(i, j));
28+
j++; // move past '#'
29+
30+
String word = s.substring(j, j + length);
31+
res.add(word);
32+
33+
i = j + length; // move to next encoded segment
34+
}
35+
36+
return res;
37+
}
38+
}

0 commit comments

Comments
 (0)