Skip to content

Commit

Permalink
feat: 271. Encode and Decode Strings
Browse files Browse the repository at this point in the history
  • Loading branch information
HC-kang committed Aug 22, 2024
1 parent 355a40c commit 9bc1fdc
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions encode-and-decode-strings/HC-kang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* The most simple way
*/
function encode(strs: string[]): string {
return strs.join('🏖️');
};
function decode(s: string): string[] {
return s.split('🏖️');
};

// T.C: O(n)
// S.C: O(n)
function encode(strs: string[]): string {
return strs.map((s) => s.length + '#' + s).join('');
}

// T.C: O(n)
// S.C: O(n)
function decode(s: string): string[] {
const res: string[] = [];
let curIdx = 0;
while (curIdx < s.length) {
const sepIdx = s.indexOf('#', curIdx);
const len = parseInt(s.slice(curIdx, sepIdx), 10);
res.push(s.slice(sepIdx + 1, sepIdx + 1 + len));
curIdx = sepIdx + 1 + len;
}
return res;
}

0 comments on commit 9bc1fdc

Please sign in to comment.