zoukankan      html  css  js  c++  java
  • [LC] 271. 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;
    }

    public class Codec {
    
        // Encodes a list of strings to a single string.
        public String encode(List<String> strs) {
            StringBuilder sb = new StringBuilder();
            for (String str: strs) {
                int len = str.length();
                sb.append(len).append("/").append(str);
            }
            return sb.toString();
        }
    
        // Decodes a single string to a list of strings.
        public List<String> decode(String s) {
            List<String> res = new ArrayList<>();
            int i = 0; 
            while (i < s.length()) {
                int slash = s.indexOf("/", i);
                int len = Integer.valueOf(s.substring(i, slash));
                res.add(s.substring(slash + 1, slash + 1 + len));
                i = slash + 1 + len;
            }
            return res;
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.decode(codec.encode(strs));
  • 相关阅读:
    MySQL轻量级监测工具—doDBA
    MySQL构建百万级数据
    MySQL备份与恢复—xtrabackup
    MySQL8.0.15二进制包安装
    「考试」省选51
    「总结」二次剩余
    「考试」省选50
    「总结」$pdf$课:$dp2$
    「考试」省选49
    「考试」省选48
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12306515.html
Copyright © 2011-2022 走看看