[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
evalor 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 ...
随机推荐
- 程序员带你十天快速入门Python,玩转电脑软件开发(一)
关注今日头条-做全栈攻城狮,学代码也要读书,爱全栈,更爱生活.提供程序员技术及生活指导干货. 如果你真想学习,请评论学过的每篇文章,记录学习的痕迹. 请把所有教程文章中所提及的代码,最少敲写三遍,达到 ...
- mysql-distinct去重、mysql-group …
一.MYSQL-distinct用法 在使用mysql时,有时需要查询出某个字段不重复的记录,虽然mysql提供有distinct这个关键字来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记 ...
- Gradle插件
1.方法数统计 classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.6.1' apply plugin: 'com.getkeep ...
- 我和ASP.NET MVC有个约会
很早之前在项目中使用的软件架构模式,一直想着写一写加深自己对它的理解.但总是一天拖着一天,趁着现在闲,跟大家唠唠嗑这个东西. 首先什么是 MVC(Model-View-Controller) 呢?不得 ...
- Java 对象属性的遍历
package com.cn.mybatis.test; import java.io.IOException; import java.io.InputStream; import java.lan ...
- IOS-UIScrollView实现图片分页
1.设置可以分页 _scrollView.pagingEnabled = YES; 2.添加PageControl UIPageControl *pageControl = [[UIPageContr ...
- 实习之vim基本学习
最近实习学到了写vim的基本用法,记录一下 批量注释 ctrl+v进入列模式,按“I”进入插入模式,按// #等在每行开头插入注释,esc 批量去除注释 ctrl + v 进入列模式,按“x”即可. ...
- android入门到熟练(二)----活动
1.活动创建对于每一个后端java类(继承至Activity或者ActionBarActivity)代码都有一个方法需要被重写[onCreate], 在此方法中可以加载界面资源文件或者绑定元素事件. ...
- NLPIR.user Not valid license or your license expired! Please feel free to contact pipy_zhang@msn.com
NLPIR.user Not valid license or your license expired! Please feel free to contact pipy_zhang@msn.com ...
- php 用于检测是PC还是手机访问
<?php$ua = strtolower($_SERVER['HTTP_USER_AGENT']);$uachar = "/(iphone|android|phone|mobile| ...