Last active
October 3, 2016 15:58
-
-
Save gcrfelix/f342257a2a124f525c4c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
题目:http://www.voidcn.com/blog/qq508618087/article/p-5704907.html | |
// new solution: 10/3/2016 | |
public class Codec { | |
// Encodes a list of strings to a single string. | |
public String encode(List<String> strs) { | |
StringBuilder sb = new StringBuilder(); | |
for(String str : strs) { | |
sb.append(str.length()).append("/").append(str); | |
} | |
return sb.toString(); | |
} | |
// Decodes a single string to a list of strings. | |
public List<String> decode(String s) { | |
List<String> result = new ArrayList<String>(); | |
int i = 0; | |
while(i < s.length()) { | |
int slash = s.indexOf("/", i); | |
int size = Integer.parseInt(s.substring(i, slash)); | |
String str = s.substring(slash+1, slash+1+size); | |
result.add(str); | |
i = slash + size + 1; | |
} | |
return result; | |
} | |
} | |
public class EncodeAndDecode { | |
public String encode(String[] strs) { | |
if(strs == null || strs.length == 0) { | |
return ""; | |
} | |
StringBuilder sb = new StringBuilder(); | |
sb.append(strs.length).append("#"); // 首先计算数组元素个数,用#分隔 | |
for(String str : strs) { | |
int len = str == null ? 0 : str.length(); | |
sb.append(len).append("%"); // 然后计算数组里每个元素长度,用%分隔 | |
} | |
for(String str : strs) { | |
sb.append(str); // 最后粘贴每个元素 | |
} | |
return sb.toString(); | |
} | |
public String[] decode(String str) { | |
if(str == null || str.length() == 0) { | |
return new String[0]; | |
} | |
String[] arrayLen = str.split("#"); | |
int arr_len = Integer.parseInt(arrayLen[0]); // 首先得到数组长度 | |
str = str.substring(arrayLen[0].length()+1); // 更新str | |
String[] wordLen = str.split("%"); | |
int[] word_len = new int[arr_len]; | |
int total = 0; | |
for(int i=0; i<arr_len; i++) { | |
word_len[i] = Integer.parseInt(wordLen[i]); // 然后得到每个元素长度 | |
total += word_len[i]; // 同时记录所有元素长度之后 方便下面更新str | |
} | |
str = str.substring(str.length()-total); // 更新str | |
String[] result = new String[arr_len]; | |
for(int i=0; i<arr_len; i++) { | |
result[i] = str.substring(0, word_len[i]); // 根据每个元素长度得到相应元素 | |
str = str.substring(word_len[i]); | |
} | |
return result; | |
} | |
public static void main(String[] args) { | |
EncodeAndDecode solution = new EncodeAndDecode(); | |
String[] arr = {"abc%cde", "a#aa", "haha"}; | |
String encode = solution.encode(arr); | |
String[] decode = solution.decode(encode); | |
System.out.println(Arrays.toString(decode)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment