Encode and Decode Strings 解答
Question
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.
Solution 1 -- JSON format
第一种方法是参考的JSON的规则。
Encode: 我们将输入的字符串数组封装成JSON中的array。[ (left bracket) and ] (right bracket) 表示开头的结尾。中间的分隔用, (comma)。然后对于每个字符串,是 wrapped in double quotes。
由于字符串中本来就可能有双引号或是back slash (\),所以我们需要对这两种符号做转义。方法是多加一个back slash
如 原字符串 \"aafg" -> \\\"aafg\"
JSON里还有更复杂的字符串处理方法。但我们这里的目标只是让encode,再decode后的字符串相同,所以不必那么复杂。
Decode处理原则如下
1. 一个boolean的variable记录当前应该是下一个字符串的开头还是当前字符串的结束
2. 碰到bracket,根据是开始/结束,新建一个空字符串/将当前的字符串存入结果中
3. 碰到back slash,看它下一个元素是否是back slash / bracket,如果是,则将它下一个元素加到字符串中,计数加一。
public class Codec {
private final char start = '[';
private final char end = ']';
private final char include = '"';
private final char strSplit = ','; // Encodes a list of strings to a single string.
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
sb.append(start);
for (String str : strs) {
sb.append(include);
int len = str.length();
for (int i = 0; i < len; i++) {
char current = str.charAt(i);
if (current == '"' || current == '\\') {
sb.append('\\');
}
sb.append(current);
}
sb.append(include);
sb.append(strSplit);
}
sb.append(end);
return sb.toString();
} // Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> result = new ArrayList<String>();
if (s == null || s.length() < 1) {
return result;
}
int len = s.length();
if (s.charAt(0) != start || s.charAt(len - 1) != end) {
return result;
}
boolean startSymbol = true;
StringBuilder sb = new StringBuilder();
for (int i = 1; i < len - 1; i++) {
char current = s.charAt(i);
if (current == include) {
if (startSymbol) {
sb = new StringBuilder();
} else {
result.add(sb.toString());
}
startSymbol = !startSymbol;
continue;
}
if (current == strSplit && startSymbol) {
continue;
}
if (current == '\\') {
char next = s.charAt(i + 1);
if (next == '\\' || next == '"') {
sb.append(next);
i++;
continue;
}
}
sb.append(current);
}
return result;
}
} // Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));
Solution 2
利用了Java里String的 int indexOf(int ch, int fromIndex)函数。
同时存入字符串和字符串的长度。
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) {
sb.append(str.length()).append('/').append(str);
}
return sb.toString();
} // Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> result = new ArrayList<String>();
int length = s.length();
int i = 0;
while (i < length) {
int slash = s.indexOf('/', i);
int size = Integer.valueOf(s.substring(i, slash));
result.add(s.substring(slash + 1, slash + size + 1));
i = slash + size + 1;
}
return result;
}
}
Encode and Decode Strings 解答的更多相关文章
- [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
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 ...
- [LeetCode#271] Encode and Decode Strings
Problem: Design an algorithm to encode a list of strings to a string. The encoded string is then sen ...
- [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 -- LeetCode
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...
- [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 ...
- [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 ...
随机推荐
- 【开源】Hawk-数据抓取工具:简明教程
1.软件介绍 HAWK是一种数据采集和清洗工具,依据GPL协议开源,能够灵活,有效地采集来自网页,数据库,文件, 并通过可视化地拖拽, 快速地进行生成,过滤,转换等操作.其功能最适合的领域,是爬虫和数 ...
- [置顶] 使用struts拦截器+注解实现网络安全要求中的日志审计功能
J2EE项目中出于安全的角度考虑,用户行为审计日志功能必不可少,通过本demo可以实现如下功能: 1.项目中记录审计日志的方法. 2.struts拦截器的基本配置和使用方法. 3.struts拦截器中 ...
- MongoDB命令行操作
本文专门介绍MongoDB的命令行操作.其实,这些操作在MongoDB官网提供的Quick Reference上都有,但是英文的,为了方便,这里将其稍微整理下,方便查阅. 这里用来做测试的是远端(10 ...
- Android 体系结构
Anroid是在Linux基础开发出的一个移动设备开发平台.它自上而下包含四个部分: Application(应用程序) Applicaton Framework(应用程序框架) Libraries& ...
- openstack中glance组件images的全部python API 汇总
感谢朋友支持本博客,欢迎共同探讨交流.因为能力和时间有限.错误之处在所难免,欢迎指正! 假设转载,请保留作者信息. 博客地址:http://blog.csdn.net/qq_21398167 原博文地 ...
- 线程、线程句柄、线程ID
什么是句柄:句柄是一种指向指针的指针.我们知道,所谓指针是一种内存地址.应用程序启动后,组成这个程序的各对象是住留在内存的.如果简单地理解,似乎我们只要获知这个内存的首地址,那么就可以随时用这个地址 ...
- My way to Python - Day04 - 模块
re模块 什么是正则表达式 正则表达式,英文叫做Regular Expression.简单说,正则表达式就是一组规则,用于实现字符串的查找,匹配,以实现关于字符串的相关操作,比如替换,删除等. 正则表 ...
- Web项目去掉Js文件红叉
项目用到jquery,但将Jquery拷进去后,js文件有个红叉,看上去非常不爽.如下图: 解决方法: 1.找到项目下的.project文件 2.去掉Javascript验证 <?xml ver ...
- 掌握jQuery插件开发,这篇文章就够了
---恢复内容开始--- 在实际开发工作中,总会碰到像滚动,分页,日历等展示效果的业务需求,对于接触过jQuery以及数据jQuery使用的人来说,首先想到的肯定是寻找现有的jQuery插件来满足形影 ...
- 表格table常见的边框设置和初步的立体效果
做网页时经常会遇到表格,常见的表格如下: <style type="text/css"> .tbtest0 { width:500px; height:200px; b ...