[LeetCode#271] Encode and Decode Strings
Problem:
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.
Note:
- The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.
- Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
- Do not rely on any library method such as
eval
or serialize methods. You should implement your own encode/decode algorithm.
Analysis:
This problem needs some skills in implementation. Once you know the tricky skill underlying it, you would think how it could be so easy!
Instant idea: Can you use some special characters to separate those strings.
Nope! No matter what kind of special characters you use, it may appear in each individual string by chance! Then I have came up with the idea to use certain number of characters to record each string's information in the overall string.
However, how much prefix characters is enough? how to sepearte the information for each string out?
That's a headache problem! The genius idea: why not combinely use special character and size information. Wrap your string in following way in the encode string.
encode_string = size1:{original_string}size2:{original_string}size3:{original_string}size4:{original_string}
each original string is wrap through following way:
original_string ---> size1:{original_string} For a single block, how could we extract the orginal_string out of wraped string?
Step 1: get the start index of the block. Inital start index is 0.
-------------------------------------------------------------------
int next_start = 0; Step 2: use ":" to get the orginal_string's length.
-------------------------------------------------------------------
int split_index = s.indexOf(":", next_start);
int len = Integer.valueOf(s.substring(next_start, split_index)); Step 3: combinely use ":" and length information to extract the original string out.
-------------------------------------------------------------------
String item = s.substring(split_index+1, split_index+1+len);
ret.add(item); Step 4: update the start index for the next string.
-------------------------------------------------------------------
next_start = split_index+1+len;
Wrong Solution:
public class Codec {
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
if (strs == null)
throw new IllegalArgumentException("strs is null");
StringBuffer buffer = new StringBuffer();
for (String str : strs) {
buffer.append(str.length());
buffer.append(":");
buffer.append(str);
}
return buffer.toString();
} // Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> ret = new ArrayList<String> ();
int next_start = 0;
int split_index = s.indexOf(":");
int len = Integer.valueOf(s.substring(next_start, split_index));
while (next_start < s.length()) {
String item = s.substring(split_index+1, split_index+1+len);
ret.add(item);
next_start = split_index+1+len;
split_index = s.indexOf(":", next_start);
len = Integer.valueOf(s.substring(next_start, split_index));
}
return ret;
}
}
Mistakes Analysis:
Last executed input:
[] Mistake Analysis:
My first implementation is complex and so ugly!!!
Since we need to do the same work for all wrapped strings, we should not allow a singly operation spill out the common block. int next_start = 0;
int split_index = s.indexOf(":"); //what if there is no string in the encoded string!!! This ugly logic incure a corner case!
int len = Integer.valueOf(s.substring(next_start, split_index));
while (next_start < s.length()) {
String item = s.substring(split_index+1, split_index+1+len);
ret.add(item);
next_start = split_index+1+len;
split_index = s.indexOf(":", next_start);
len = Integer.valueOf(s.substring(next_start, split_index));
} What's more, "while (next_start < s.length())" is great checking for cases!
Solution:
public class Codec {
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
if (strs == null)
throw new IllegalArgumentException("strs is null");
StringBuffer buffer = new StringBuffer();
for (String str : strs) {
buffer.append(str.length());
buffer.append(":");
buffer.append(str);
}
return buffer.toString();
} // Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> ret = new ArrayList<String> ();
int next_start = 0;
while (next_start < s.length()) {
int split_index = s.indexOf(":", next_start);
int len = Integer.valueOf(s.substring(next_start, split_index));
String item = s.substring(split_index+1, split_index+1+len);
ret.add(item);
next_start = split_index+1+len;
}
return ret;
}
} // Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));
[LeetCode#271] Encode and Decode Strings的更多相关文章
- [LeetCode] 271. Encode and Decode Strings 加码解码字符串
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...
- 271. Encode and Decode Strings
题目: Design an algorithm to encode a list of strings to a string. The encoded string is then sent ove ...
- [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 th ...
- [LeetCode] Encode and Decode Strings 加码解码字符串
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...
- LeetCode Encode and Decode Strings
原题链接在这里:https://leetcode.com/problems/encode-and-decode-strings/ 题目: Design an algorithm to encode a ...
- Encode and Decode Strings -- LeetCode
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...
- [Swift]LeetCode271. 加码解码字符串 $ Encode and Decode Strings
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...
- Encode and Decode Strings
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...
- Encode and Decode Strings 解答
Question Design an algorithm to encode a list of strings to a string. The encoded string is then sen ...
随机推荐
- HTML+CSS基础学习笔记(6)
一.元素分类 CSS中html的标签元素大体分为三种类型 1.块状元素 @特点: #每个块级元素都从新的一行开始,并且其后的元素也另起一行(一个块级元素独占一行) #元素的高度.宽度.行高以及顶和底边 ...
- js 的执行过程
step 1. 读入第一个代码块. step 2. 做语法分析,有错则报语法错误(比如括号不匹配等),并跳转到step5. step 3. 对var变量和function定义做"预编译 ...
- Centos6.5 安装 MariaDB-10.0.20-linux-x86_64.tar.gz
下载mariadb :https://downloads.mariadb.org/ 我选择mariadb-10.0.20-linux-x86_64.tar.gz这个版本 复制安装文件 /opt 目录 ...
- CSS之关于clearfix--清除浮动
一,什么是.clearfix 你只要到Google或者Baidu随便一搜"css清除浮动",就会发现很多网站都讲到"盒子清除内部浮动时可以用到.clearfix" ...
- SQL Server中Id自增列的最大Id是多少
什么是自增列 在SQL Server中可以将Id列设为自增.即无需为Id指定值,由SQL Server自动给该列赋值,每新增一列Id的值加一,初始值为1. 需要注意的是即使将原先添加的所有数据都删除, ...
- IE str.trim() 不兼容问题解决方法
本文实例分析了javascript在IE下trim函数无法使用的解决方法: 首先,javascript的trim函数在firefox或者chrome下面使用没有问题: 1 2 3 4 5 <sc ...
- struts2 测试错题解析
解析:$.parseJSON()方法是将字符串转换成Json类型数据,$.getJSON()方法是获取JSON数据,两者不用联合使用. 解析: A:ActionContext接口没有getReques ...
- 让USB键盘的LED灯听你的!(不干扰使用)
最近在研究一个课题,如何能利用键盘的led灯通道进行有效通信,那么首先要做的就是尝试能否在不影响键盘的情况下控制LED灯(num lock ,caps lock ,scroll lock)的使用. 首 ...
- js获取上传文件信息并及时查看
<form id="picForm" name="picForm" method="post" enctype="mult ...
- Python函数式编程初级学习
函数式编程即函数可以作为参数传入函数,也可以返回函数. 1.高阶函数 函数可以作为参数传入函数. def add(x,y,f): return f(x)+f(y) ...