271. Encode and Decode Strings

2021-11-20  本文已影响0人  jluemmmm

设计一种算法,将字符串列表编码为字符串。 编码后的字符串然后通过网络发送并解码回原始字符串列表。

/**
 * Encodes a list of strings to a single string.
 *
 * @param {string[]} strs
 * @return {string}
 */
var encode = function(strs) {
  return strs.reduce((res, cur) => {
    return res+= (cur.length + '|' + cur);
  }, '')
};


/**
 * Decodes a single string to a list of strings.
 *
 * @param {string} s
 * @return {string[]}
 */
var decode = function(s) {
  const res = [];
  while (s) {
    const index = s.indexOf('|');
    const len = parseInt(s.substr(0, index));
    res.push(s.substring(index + 1, index + len + 1))
    s = s.substr(index + len + 1);
  }
  return res;
};

/**
 * Your functions will be called as such:
 * decode(encode(strs));
 */
上一篇 下一篇

猜你喜欢

热点阅读