-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncodeAndDeodeStringsM1.java
More file actions
62 lines (50 loc) · 1.8 KB
/
EncodeAndDeodeStringsM1.java
File metadata and controls
62 lines (50 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Leetcode problem #271, Encode and Decode Strings
* https://leetcode.com/problems/encode-and-decode-strings/
*
* Using Escaping, '/' as escape character, with delimiter as "/:"
*/
public class EncodeAndDeodeStringsM1 {
public static void main(String[] args) {
List<String> strs = new ArrayList<>(Arrays.asList("Hello", "World"));
Codec codec = new Codec();
String encodedString = codec.encode(strs);
System.out.println(encodedString);
System.out.println(codec.decode(encodedString));
}
static class Codec {
// Encode list of strings to a single string
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for (String s : strs) {
sb.append(s.replace("/", "//")).append("/:");
}
return sb.toString();
}
// Decodes a single string to a list of strings
public List<String> decode(String s) {
List<String> strs = new ArrayList<>();
StringBuilder sb = new StringBuilder();
int len = s.length();
int i = 0;
while (i < s.length()) {
// If we encounter delimiter /:
if (i + 1 < len && s.charAt(i) == '/' && s.charAt(i + 1) == ':') {
strs.add(sb.toString());
sb = new StringBuilder();
i += 2;
} else if (i + 1 < len && s.charAt(i) == '/' && s.charAt(i + 1) == '/') {
sb.append('/');
i += 2;
} else {
sb.append(s.charAt(i));
i++;
}
}
return strs;
}
}
}