[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 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
evalor serialize methods. You should implement your own encode/decode algorithm.
给字符加码再解码,先有码再无码,题目没有限制加码的方法,那么只要能成功的把有码变成无码就行了,具体变换方法自己设计。
Java:
public String encode(List<String> strs) {
StringBuffer out = new StringBuffer();
for (String s : strs)
out.append(s.replace("#", "##")).append(" # ");
return out.toString();
}
public List<String> decode(String s) {
List strs = new ArrayList();
String[] array = s.split(" # ", -1);
for (int i=0; i<array.length-1; ++i)
strs.add(array[i].replace("##", "#"));
return strs;
}
Java: with streaming
public String encode(List<String> strs) {
return strs.stream()
.map(s -> s.replace("#", "##") + " # ")
.collect(Collectors.joining());
}
public List<String> decode(String s) {
List strs = Stream.of(s.split(" # ", -1))
.map(t -> t.replace("##", "#"))
.collect(Collectors.toList());
strs.remove(strs.size() - 1);
return strs;
}
Java:
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
StringBuilder output = new StringBuilder();
for(String str : strs){
// 对于每个子串,先把其长度放在前面,用#隔开
output.append(String.valueOf(str.length())+"#");
// 再把子串本身放在后面
output.append(str);
}
return output.toString();
} // Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> res = new LinkedList<String>();
int start = 0;
while(start < s.length()){
// 找到从start开始的第一个#,这个#前面是长度
int idx = s.indexOf('#', start);
int size = Integer.parseInt(s.substring(start, idx));
// 根据这个长度截取子串
res.add(s.substring(idx + 1, idx + size + 1));
// 更新start为子串后面一个位置
start = idx + size + 1;
}
return res;
}
Java: better
public String encode(List<String> strs) {
StringBuffer result = new StringBuffer();
if(strs == null || strs.size() == 0)
return result.toString();
for(String str: strs){
result.append(str.length());
result.append("#");
result.append(str);
}
return result.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> result = new ArrayList();
if(s == null || s.length() == 0)
return result;
int current = 0;
while(true){
if(current == s.length())
break;
StringBuffer sb = new StringBuffer();
while(s.charAt(current) != '#'){
sb.append(s.charAt(current));
current++;
}
int len = Integer.parseInt(sb.toString());
int end = current + 1 + len;
result.add(s.substring(current+1, end));
current = end;
}
return result;
}
Java: Time Complexity - O(n), Space Complexity - O(1)
public class Codec {
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
if(strs == null || strs.size() == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for(String s : strs) {
int len = s.length();
sb.append(len);
sb.append('/');
sb.append(s);
}
return sb.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> res = new ArrayList<>();
if(s == null ||s.length() == 0) {
return res;
}
int index = 0;
while(index < s.length()) {
int forwardSlashIndex = s.indexOf('/', index);
int len = Integer.parseInt(s.substring(index, forwardSlashIndex));
res.add(s.substring(forwardSlashIndex + 1, forwardSlashIndex + 1 + len));
index = forwardSlashIndex + 1 + len;
}
return res;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));
Java: Time Complexity - O(n), Space Complexity - O(n)
public class Codec {
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for (String s : strs) {
sb.append(s.length()).append('#').append(s);
}
return sb.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> res = new ArrayList<>();
if (s == null || s.length() == 0) return res;
for (int lo = 0, i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '#') {
int len = Integer.parseInt(s.substring(lo, i));
res.add(s.substring(i + 1, i + 1 + len));
lo = i + 1 + len;
i = i + 1 + len;
}
}
return res;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));
Python:
# Time: O(n)
# Space: O(1)
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
encoded_str = ""
for s in strs:
encoded_str += "%0*x" % (8, len(s)) + s
return encoded_str def decode(self, s):
"""Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
i = 0
strs = []
while i < len(s):
l = int(s[i:i+8], 16)
strs.append(s[i+8:i+8+l])
i += 8+l
return strs
C++:
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string res = "";
for (auto a : strs) {
res.append(to_string(a.size())).append("/").append(a);
}
return res;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> res;
int i = 0;
while (i < s.size()) {
auto found = s.find("/", i);
int len = atoi(s.substr(i, found).c_str());
res.push_back(s.substr(found + 1, len));
i = found + len + 1;
}
return res;
}
};
C++:
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string res = "";
for (auto a : strs) {
res.append(to_string(a.size())).append("/").append(a);
}
return res;
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> res;
while (!s.empty()) {
int found = s.find("/");
int len = atoi(s.substr(0, found).c_str());
s = s.substr(found + 1);
res.push_back(s.substr(0, len));
s = s.substr(len);
}
return res;
}
};
All LeetCode Questions List 题目汇总
[LeetCode] 271. 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#271] Encode and Decode Strings
Problem: Design an algorithm to encode a list of strings to a string. The encoded string is then sen ...
- 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 ...
- [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 ...
- 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 ...
- [LeetCode] 535. Encode and Decode TinyURL 编码和解码短网址
Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL sho ...
- Encode and Decode Strings
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...
随机推荐
- 使用gitlab下载代码(附常用命令)
Git是现在很多人常用的代码管理工具,这里有一些常用的命令详解,本人接触也不是很久,若有错误,请在评论指出,谢谢. 若计算机中没有安装GIT,可自行查找安装教程,十分简便. ①首先,我们需要下载项目, ...
- WinForm利用AForge.NET调用电脑摄像头进行拍照和视频
当然了,你需要去官网下载类库,http://www.aforgenet.com/ 调用本机摄像头常用的组件: AForge AForge.Controls AForge.Imaging AForge. ...
- 项目Alpha冲刺(10/10)
1.项目燃尽图 2.今日进度描述 项目进展 完成测试 问题困难 测试用例的设计 心得体会 目标快要完成,队员士气较高 3.会议照片 4.各成员情况 221600106 今日进展 根据测试结果修改代码 ...
- 我理解的Linux内存管理
众所周知,内存管理是Linux内核中最基础,也是相当重要的部分.理解相关原理,不管是对内存的理解,还是对大家写用户态代码都很有帮助.很多书上.很多文章都写了相关内容,但个人总觉得内容太复杂,不是太容易 ...
- treegrid 折叠全部节点
$(".easyui-treegrid").treegrid({ url: '@Url.Action("GetDataDictionaryList", &quo ...
- BZOJ-1975: 魔法猪学院 (K短路:A*+SPFA)
题意:有N种化学元素,有M种转化关系,(u,v,L)表示化学物质由u变为v需要L能量,现在你有E能量,问最多有多少种不同的途径,使得1转为为N,且总能量不超过E. 思路:可以转为为带权有向图,即是求前 ...
- lis框架showoncodename的用法
fm.Sex.value=tContent2[0][3];//这个一定得是查询出来的码值alert("获取到的值是:"+tContent2[0][3]);showOneCodeNa ...
- 题解 UVa11752
题目大意 输出所有小于 \(2^{64}-1\) 的正整数 \(n\), 使得 \(\exists p, q, a, b\in \mathbb{N+}, p\neq q\rightarrow a^p= ...
- Eclipse 打包运行maven项目
https://www.cnblogs.com/tangshengwei/p/6341462.html
- react用脚手架创建一个react单页面项目,react起手式
官网地址:https://react.docschina.org/ 确保本地安装了Node.js node的版本大于8.10 npm的版本大于5.6 1.在本地的某个位置创建一个文件夹,执行以下 ...