Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 133cd80

Browse files
committedMay 3, 2025·
solve encode and decode string
1 parent a404177 commit 133cd80

File tree

1 file changed

+33
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)
Please sign in to comment.