Skip to content

Commit e66402c

Browse files
committed
encode-and-decode-strings solution
1 parent 1510668 commit e66402c

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
private baseStr = "#";
3+
/*
4+
* @param strs: a list of strings
5+
* @return: encodes a list of strings to a single string.
6+
*/
7+
public encode(strs: string[]): string {
8+
let encodedStr = "";
9+
for (const str of strs) {
10+
encodedStr += `${str.length}${this.baseStr}${str}`;
11+
}
12+
return encodedStr;
13+
}
14+
15+
/*
16+
* @param str: A string
17+
* @return: decodes a single string to a list of strings
18+
*/
19+
public decode(str: string): string[] {
20+
const spliter = [];
21+
let idx = 0;
22+
while (idx < str.length) {
23+
let findBase = idx;
24+
// length가 10 이상일 경우를 위해 순회하며 파싱
25+
while (str[findBase] !== this.baseStr) {
26+
findBase++;
27+
}
28+
29+
const contentLength = parseInt(str.substring(idx, findBase));
30+
const content = str.substring(findBase + 1, findBase + contentLength + 1);
31+
spliter.push(content);
32+
idx = findBase + contentLength + 1;
33+
}
34+
return spliter;
35+
}
36+
}
37+
38+
const input = ["lint", "code", "love", "you"];
39+
40+
const solutionInstance = new Solution();
41+
42+
const encoded = solutionInstance.encode(input);
43+
const decoded = solutionInstance.decode(encoded);
44+
45+
console.log(encoded, decoded);
46+
47+

0 commit comments

Comments
 (0)