271. Encode and Decode Strings
居然要premium才能做,果断换LintCode来写这题
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.
Please implement encode and decode
Example
Input: ["lint","code","love","you"]
Output: ["lint","code","love","you"]
Explanation:
One possible encode method is: "lint:;code:;love:;you"
思路
只要知道每一个String长度,然后记录他的长度,那解码的时候就可以依据他的长度,拿到该String,关键在于只存长度还是有点问题,因为如果String中也有数字,那就不知道在哪边截断,取出正确的字符串长度,所以可以自定义一个字符。
规则应该是String.length + Special Char + String
题解
- 无脑快速AC
/*
* @param strs: a list of strings
* @return: encodes a list of strings to a single string.
*/
public String encode(List<String> strs) {
// write your code here
String res = "";
for (String val : strs) {
res += (val.length() + "," + val);
}
return res;
}
/*
* @param str: A string
* @return: dcodes a single string to a list of strings
*/
public List<String> decode(String str) {
// write your code here
ArrayList<String> result = new ArrayList<>();
while (!str.equals("")) {
// 拿到截断字符串的下标,
int splitIndex = str.indexOf(",");
// 通过该下标,直接截断字符串取出当前待解码字符串长度
Integer strLength = Integer.valueOf(str.substring(0, splitIndex));
// 设置待解码字符串在当前编码字符串中的起始位置
int start = splitIndex + 1;
// 算出结束位
int end = start + strLength;
String curStr = str.substring(start, end);
result.add(curStr);
// 直接将当前已插入结果集的子串截去,substring不太熟练,+1-1搞晕
str = str.substring(end);
}
return result;
}
标签:code,String,list,Decode,271,str,Encode,strings,string
From: https://www.cnblogs.com/tanhaoo/p/17038323.html