美文网首页
271. Encode and Decode Strings

271. Encode and Decode Strings

作者: jluemmmm | 来源:发表于2021-11-20 14:41 被阅读0次

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

    • 时间复杂度O(n),空间复杂度O(1)
    • Runtime: 96 ms, faster than 71.78%
    • Memory Usage: 44.5 MB, less than 71.78%
    /**
     * 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));
     */
    

    相关文章

      网友评论

          本文标题:271. Encode and Decode Strings

          本文链接:https://www.haomeiwen.com/subject/asnstrtx.html