[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
eval
or 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 ...
随机推荐
- django--学习笔记 一
django--学习笔记 一 简介 本次笔记来源于对django官方教程的学习总结,点击进入官方教程. 要点 1.django框架简单介绍: 2.如何创建项目,创建项目介绍: 3.如何在项目在创建应用 ...
- python——selenium库的使用
selenium 是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Fire ...
- Python基础初始之二
1.格式化的输出 当你遇到这样的需要:字符串中想让某些位置变成动态可传入的,首先考虑用格式化输出 1.格式化输出:% 2. 格式化输出:format 3. 格式化输出:f 2.运算符 3.编码 待续
- PC端自适应布局
截止目前,国内绝大多数内容为主的网站(知乎,果壳,V2EX,网易新闻等)均使用内容区定宽布局,大多数电商网站(网易考拉,京东,聚美优品)也使用了内容区定宽的布局,也有些网站使用了自适应布局: 天猫 内 ...
- css 的弱化与 js 的强化(转)
web 的三要素 html, css, js 在前端组件化的过程中,比如 react.vue 等组件化框架的运用,使 html 的弱化与 js 的强化 成为了一种趋势,而在这个过程中,其实还有另一种趋 ...
- Python 代码混淆和加密技术
动机 Python进行商业开发时, 需要有一定的安全意识, 为了不被轻易的逆向. 混淆和加密就有所必要了. 混淆 为了增加代码阅读的难度, 源代码的混淆非常必要, 一个在线的Python代码混淆网站. ...
- gin+redis
var RedisDefaultPool *redis.Pool func newPool(addr string) *redis.Pool { return &redis.Pool{ Max ...
- learing java NIO 之 ReadFile
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...
- 14-ESP8266 SDK开发基础入门篇--上位机串口控制 Wi-Fi输出PWM的占空比,调节LED亮度,8266程序编写
https://www.cnblogs.com/yangfengwu/p/11102026.html 首先规定下协议 ,CRC16就不加了哈,最后我会附上CRC16的计算程序,大家有兴趣自己加上 上 ...
- Flutter 简介(事件、路由、异步请求)
1. 前言 Flutter是一个由谷歌开发的开源移动应用软件开发工具包,用于为Android和iOS开发应用,同时也将是Google Fuchsia下开发应用的主要工具.其官方编程语言为Dart. 同 ...