[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:
1 |
|
So Machine 1 does:
1 |
|
and Machine 2 does:
1 |
|
strs2 in Machine 2 should be the same as strs in Machine 1.
Implement the encode and decode methods.
You are not allowed to solve the problem using any serialize methods (such as eval).
Example 1:
Input: dummy_input = [“Hello”,”World”]
Output: [“Hello”,”World”]
Explanation:
Machine 1:
Codec encoder = new Codec();
String msg = encoder.encode(strs);
Machine 1 —msg—> Machine 2
Machine 2:
Codec decoder = new Codec();
String[] strs = decoder.decode(msg);
Example 2:
Input: dummy_input = [“”]
Output: [“”]
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] contains any possible characters out of 256 valid ASCII characters.
Follow up: Could you write a generalized algorithm to work on any possible set of characters?
字符串的编码与解码。
请你设计一个算法,可以将一个 字符串列表 编码成为一个 字符串。这个编码后的字符串是可以通过网络进行高效传送的,并且可以在接收端被解码回原来的字符串列表。
思路
对于 input 给的字符串列表,我们可以把他压缩成这种形式
单词长度size + ‘,’ + 单词
那么对于一个单词列表 [hello, world, hello, world] 而言,他将会被压缩成这个样子。
5,hello5,world5,hello5,world
所以当我们试着再把这个字符串变回 字符串列表 的时候,我们可以用 string.indexOf(‘,’) 找到每一个逗号的位置,找到逗号之后,当前位置到逗号 [i, comma) 就是单词的长度 size,[comma + 1, comma + 1 + size) 则是单词本身。
复杂度
时间O(n)
空间O(n)
代码
Java实现
1 |
|
JavaScript实现
1 |
|
相关题目
1 |
|