• LeetCode 271. Encode and Decode Strings


    原题链接在这里:https://leetcode.com/problems/encode-and-decode-strings/

    题目:

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

    Machine 1 (sender) has the function:

    string encode(vector<string> strs) {
      // ... your code
      return encoded_string;
    }

    Machine 2 (receiver) has the function:

    vector<string> decode(string s) {
      //... your code
      return strs;
    } 

    So Machine 1 does:

    string encoded_string = encode(strs);

    and Machine 2 does:

    vector<string> strs2 = decode(encoded_string);

    strs2 in Machine 2 should be the same as strs in Machine 1.

    Implement the encode and decode methods.

    题解:

    encode 时维护一个stringbuilder, 对于每一个string, sb append 该string长度 + "/" + string内容.

    decode 时开始index = 0, while index < s.length(), 利用indexOf("/", fromIndex)找index 后面第一个 "/"的index, index 与 "/"index 之间是长度,解析后面该长度的string, 更新index到"/"index + 1 + len.

    Time Complexity: encode, O(n). decode, O(n). n是strs list的所有string包含所有char的个数.

    Space: O(n). StringBuilder sb 大小.

    AC Java:

     1 public class Codec {
     2 
     3     // Encodes a list of strings to a single string.
     4     public String encode(List<String> strs) {
     5         if(strs == null || strs.size() == 0){
     6             return "";
     7         }
     8         StringBuilder sb = new StringBuilder();
     9         for(String s : strs){
    10             int len = s.length();
    11             sb.append(len).append("/");
    12             sb.append(s);
    13         }
    14         return sb.toString();
    15     }
    16 
    17     // Decodes a single string to a list of strings.
    18     public List<String> decode(String s) {
    19         List<String> res = new ArrayList<String>();
    20         if(s == null || s.length() == 0){
    21             return res;
    22         }
    23         int index = 0;
    24         while(index < s.length()){
    25             int forwardInd = s.indexOf("/", index);
    26             int len = Integer.valueOf(s.substring(index, forwardInd));
    27             res.add(s.substring(forwardInd+1,forwardInd+1+len));
    28             index = forwardInd + 1 + len;
    29         }
    30         return res;
    31     }
    32 }
    33 
    34 // Your Codec object will be instantiated and called as such:
    35 // Codec codec = new Codec();
    36 // codec.decode(codec.encode(strs));

    类似Serialize and Deserialize Binary TreeSerialize and Deserialize N-ary Tree.

  • 相关阅读:
    【机器学习】浅谈协方差
    python {}.format
    【机器学习】准确率、精确率、召回率
    【声纹识别】 EER
    【机器学习】 最形象的入门
    逻辑卷-LVM
    RAID及软RAID的实现
    输入数字or 字符串,统计重复次数---字典统计练习
    Python-数据结构之dict(字典*****)
    POJ 3204 网络流的必须边
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5240944.html
Copyright © 2020-2023  润新知