* String - Delimiter
* Time O(N) | Space O(1)
* https://leetcode.com/problems/encode-and-decode-strings/
* @param {string[]} strs
* @return {string}
*/
var encode = (strs) => {
return strs
.map(
(str) => `${str.length}#${str}`,
)
.join('');
};
* String - Delimiter
* Time O(N * K) | Space O(N)
* https://leetcode.com/problems/encode-and-decode-strings/
* @param {string} str
* @return {string[]}
*/
var decode = (str, index = 0, decodedWords = []) => {
while (index < str.length) {
const { nextIndex, word } = delimitWord(
str,
index,
);
decodedWords.push(
word,
);
index = nextIndex;
}
return decodedWords;
};
const delimitWord = (str, index) => {
const delimiter = str.indexOf('#', index);
const length = Number(str.slice(index, delimiter));
const [start, end] = [delimiter + 1, delimiter + length + 1];
const word = str.slice(
start,
end,
);
return {
nextIndex: end,
word,
};
};
* Non-ASCII Delimiter - Ignore Auxiliary Space
* Time O(N) | Space O(1)
* https://leetcode.com/problems/encode-and-decode-strings/
* @param {string[]} strs
* @return {string}
*/
var encode = (strs, nonASCIICode = String.fromCharCode(257)) => {
return strs.join(
nonASCIICode,
);
};
* Non-ASCII Delimiter - Ignore Auxiliary Space
* Time O(N) | Space O(1)
* https://leetcode.com/problems/encode-and-decode-strings/
* @param {string[]} strs
* @return {string}
*/
var decode = (strs, nonASCIICode = String.fromCharCode(257)) => {
return strs.split(
nonASCIICode,
);
};
* Chunk Transfer Encoding
* Time O(N) | Space O(1)
* https://leetcode.com/problems/encode-and-decode-strings/
* @param {string[]} strs
* @return {string}
*/
var encode = (strs, sb = []) => {
for (const str of strs) {
const code = getCode(str);
const encoding = `${code}${str}`;
sb.push(encoding);
}
return sb.join('');
};
const getCode = (str) => str.length.toString(2).padStart(8, '0');
* Chunk Transfer Encoding
* Time O(N) | Space O(1)
* https://leetcode.com/problems/encode-and-decode-strings/
* @param {string} str
* @return {string[]}
*/
var decode = (str, output = []) => {
for (
let left = 0, right = left + 8, length = 0;
left < str.length;
left = right + length, right = left + 8
) {
const countString = str.slice(
left,
right,
);
length = parseInt(countString, 2);
const decoding = str.slice(
right,
right + length,
);
output.push(decoding);
}
return output;
};