Skip to content

Commit 4f3a4ba

Browse files
committed
add encode and decode strings
1 parent d63fdbd commit 4f3a4ba

File tree

4 files changed

+71
-0
lines changed

4 files changed

+71
-0
lines changed

encode-and-decode-strings/Codec.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Solution.java

encode-and-decode-strings/README.md

Whitespace-only changes.
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
public class Codec {
2+
3+
static final int MAX_LEN = Integer.toHexString(Integer.MAX_VALUE).length();
4+
5+
// lazy ... should be byte[]
6+
static final String NUM_PATTERN = "%0" + MAX_LEN + "x";
7+
8+
String serializeNumber(int n){
9+
return String.format(NUM_PATTERN, n);
10+
}
11+
12+
int deserializeNumber(char[] s, int offset){
13+
return Integer.parseInt(new String(s, offset, MAX_LEN), 16);
14+
}
15+
16+
/* [count] [str len] [str ...] ... [str len][str ... ]
17+
* 0 L 2L 2L + strlen nL (n + 1)L (n + 1)L + strlen
18+
*/
19+
20+
// Encodes a list of strings to a single string.
21+
public String encode(List<String> strs) {
22+
StringBuilder sb = new StringBuilder();
23+
sb.append(serializeNumber(strs.size()));
24+
25+
for(String s : strs){
26+
sb.append(serializeNumber(s.length()));
27+
sb.append(s);
28+
}
29+
30+
return sb.toString();
31+
}
32+
33+
// Decodes a single string to a list of strings.
34+
public List<String> decode(String s) {
35+
char[] S = s.toCharArray();
36+
37+
int offset = 0;
38+
int n = deserializeNumber(S, offset);
39+
// move to first str len start
40+
offset += MAX_LEN;
41+
42+
ArrayList<String> strs = new ArrayList<>(n);
43+
44+
for(int i = 0; i < n; i++){
45+
46+
int len = deserializeNumber(S, offset);
47+
48+
// move to str start
49+
offset += MAX_LEN;
50+
51+
strs.add(new String(S, offset, len));
52+
53+
// move to next str len start
54+
offset += len;
55+
}
56+
57+
return strs;
58+
}
59+
}
60+
61+
// Your Codec object will be instantiated and called as such:
62+
// Codec codec = new Codec();
63+
// codec.decode(codec.encode(strs));

encode-and-decode-strings/index.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
layout: solution
3+
title: Encode and Decode Strings
4+
date: 2015-09-03 13:28:10+08:00
5+
leetcode_id: 271
6+
---
7+
{% include_relative README.md %}

0 commit comments

Comments
 (0)