博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Encode and Decode Strings
阅读量:4687 次
发布时间:2019-06-09

本文共 2296 字,大约阅读时间需要 7 分钟。

原题链接在这里:

题目:

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
strs) { // ... your code return encoded_string;}

Machine 2 (receiver) has the function:

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

So Machine 1 does:

string encoded_string = encode(strs);

and Machine 2 does:

vector
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
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
decode(String s) {19 List
res = new ArrayList
();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));

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5240944.html

你可能感兴趣的文章
流程控制 Day06
查看>>
Linux下安装Tomcat
查看>>
windows live writer 2012 0x80070643
查看>>
C程序的启动和终止
查看>>
tomcat 和MySQL的安装
查看>>
11.5 内部类
查看>>
Cosine Similarity
查看>>
halt和shutdown 的区别
查看>>
git常用操作
查看>>
京东SSO单点登陆实现分析
查看>>
u-boot启动第一阶段
查看>>
MySQL批量SQL插入性能优化
查看>>
定义列属性:null,default,PK,auto_increment
查看>>
用户画像展示
查看>>
C#中StreamReader读取中文出现乱码
查看>>
使用BufferedReader的时候出现的问题
查看>>
linux安装图形界面
查看>>
Android广播发送失败
查看>>
博弈论之入门小结
查看>>
解决IE8下opacity属性失效问题,无法隐藏元素
查看>>