Skip to content

Commit 628bc9e

Browse files
authored
encode-and-decode-string 풀이 추가
1 parent 007f326 commit 628bc9e

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/**
2+
* Because the string may contain any of the 256 legal ASCII characters, your algorithm must be able to handle any character that may appear
3+
*
4+
* Example 1:
5+
* Input: ["lint","code","love","you"]
6+
* Output: ["lint","code","love","you"]
7+
* Explanation:
8+
* One possible encode method is: "lint:;code:;love:;you"
9+
*
10+
* Example 2:
11+
* Input: ["we", "say", ":", "yes"]
12+
* Output: ["we", "say", ":", "yes"]
13+
* Explanation:
14+
* One possible encode method is: "we:;say:;:::;yes"
15+
*
16+
*
17+
*
18+
* encode:
19+
* result = ""
20+
* loop strs,
21+
*
22+
* loop str,
23+
* char to charCode
24+
* not last str AND last char ? charCode + "*"
25+
* not last str AND not last char ? charCode + "+"
26+
*
27+
*
28+
*
29+
* decode:
30+
* strs = []
31+
* split str with "*", => ["12+79+NaN", "92+32"]
32+
* split each element with "+", => [ ["12", "79", "NaN"], ["92", "32"] ]
33+
* loop outer array,
34+
* str = null
35+
* loop inner array,
36+
* element is "NaN" ? ""
37+
* element is not "NaN" ? String.fromCharCode(Number(element))
38+
* str +=
39+
* str is not null ? strs.push(str)
40+
*
41+
*/
42+
43+
// TC: O(N)
44+
// SC: O(N)
45+
class Solution {
46+
encode (strs: string[]): string {
47+
return strs.map((str) => {
48+
if(str.length === 0) {
49+
return "EMPTY"
50+
}
51+
const codes = [];
52+
for(let i = 0; i < str.length; i++) {
53+
codes.push(str.charCodeAt(i));
54+
}
55+
return codes.join('+');
56+
}).join("*")
57+
58+
}
59+
60+
decode(str: string): string[] {
61+
if(str.length === 0) {
62+
return [];
63+
}
64+
65+
return str.split("*").map((encodedStr) => {
66+
if(encodedStr === "EMPTY") {
67+
return "";
68+
}
69+
70+
return encodedStr
71+
.split("+")
72+
.map((code) => String.fromCharCode(Number(code)))
73+
.join("");
74+
})
75+
}
76+
}
77+
const solution = new Solution();
78+
79+
80+
81+
const tc = [
82+
["lint","code","love","you"], // "72+79+80+94*12+34+56+78*"
83+
["we", "say", ":", "yes"],
84+
["", "a", "", "b"], // "NaN*74*NaN*75"
85+
[";::''',,,,.....", ".....,,,,'''::;"],
86+
]
87+
88+
function runTc(tc: string[]): boolean {
89+
const encoded = solution.encode(tc);
90+
const decoded = solution.decode(encoded);
91+
if(tc.length !== decoded.length) {
92+
return false;
93+
}
94+
95+
return tc.every((el, idx) => el === decoded[idx]);
96+
}
97+
98+
const totalTc = tc.length;
99+
const failedTc = tc.reduce((acc, cur) => runTc(cur) ? acc : acc+1, 0);
100+
101+
console.log(`success: ${totalTc-failedTc}/${totalTc}`);
102+

0 commit comments

Comments
 (0)