-
Notifications
You must be signed in to change notification settings - Fork 43
/
EncodeAndDecodeStrings.java
282 lines (255 loc) · 10.2 KB
/
EncodeAndDecodeStrings.java
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package LeetCodeJava.String;
// https://leetcode.com/problems/encode-and-decode-strings/
// https://leetcode.ca/all/271.html
/**
* 271. Encode and Decode Strings
* 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 eval or serialize methods. You should implement your own encode/decode algorithm.
* Difficulty:
* Medium
* Lock:
* Prime
* Company:
* Bloomberg Google Microsoft Square Twitter
*
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));
public class EncodeAndDecodeStrings {
// V0
// TODO : implement it
// Encodes a list of strings to a single string.
// V0'
// IDEA : STRING, ARRAY OP
public String encode_0(List<String> strs) {
StringBuilder encodedString = new StringBuilder();
// Iterate through the list of strings
for (String s : strs) {
// Append each string to the StringBuilder followed by the delimiter
encodedString.append(s);
encodedString.append("π");
}
// Return the entire encoded string
return encodedString.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode_0(String s) {
// Split the encoded string at each occurrence of the delimiter
// Note: We use -1 as the limit parameter to ensure trailing empty strings are included
/**
*
* In the given code, split("π", -1) is splitting a
* string s using the delimiter "π". The second argument, -1,
* is used to control the behavior of the split operation.
*
* When you use -1 as the second argument in the split method,
* it indicates that you want to include all trailing empty strings
* in the resulting array. -> `This means that if there are consecutive
* delimiters at the end of the input string, the split method
* will include empty strings for each of those delimiters.`
*
*
* Example :
*
* String s = "appleπbananaπ";
* String[] decodedStrings = s.split("π", -1);
* System.out.println(Arrays.toString(decodedStrings));
*
* # result:
*
* [apple, banana, ]
*
*
*/
String[] decodedStrings = s.split("π", -1);
// Convert the array to a list and return it
// Note: We remove the last element because it's an empty string resulting from the final delimiter
return new ArrayList<>(Arrays.asList(decodedStrings).subList(0, decodedStrings.length - 1));
}
// V1
// IDEA : Non-ASCII delimiter
// https://leetcode.com/problems/encode-and-decode-strings/editorial/
// Encodes a list of strings to a single string.
public String encode_2(List<String> strs) {
StringBuilder encodedString = new StringBuilder();
// Iterate through the list of strings
for (String s : strs) {
// Append each string to the StringBuilder followed by the delimiter
encodedString.append(s);
encodedString.append("π");
}
// Return the entire encoded string
return encodedString.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode_2(String s) {
// Split the encoded string at each occurrence of the delimiter
// Note: We use -1 as the limit parameter to ensure trailing empty strings are included
/**
*
* In the given code, split("π", -1) is splitting a
* string s using the delimiter "π". The second argument, -1,
* is used to control the behavior of the split operation.
*
* When you use -1 as the second argument in the split method,
* it indicates that you want to include all trailing empty strings
* in the resulting array. -> `This means that if there are consecutive
* delimiters at the end of the input string, the split method
* will include empty strings for each of those delimiters.`
*
*
* Example :
*
* String s = "appleπbananaπ";
* String[] decodedStrings = s.split("π", -1);
* System.out.println(Arrays.toString(decodedStrings));
*
* # result:
*
* [apple, banana, ]
*
*
*/
String[] decodedStrings = s.split("π", -1);
// Convert the array to a list and return it
// Note: We remove the last element because it's an empty string resulting from the final delimiter
return new ArrayList<>(Arrays.asList(decodedStrings).subList(0, decodedStrings.length - 1));
}
// V2
// IDEA : Escaping
// https://leetcode.com/problems/encode-and-decode-strings/editorial/
// Encodes a list of strings to a single string.
public String encode_3(List<String> strs) {
// Initialize a StringBuilder to hold the encoded strings
StringBuilder encodedString = new StringBuilder();
// Iterate over each string in the input list
for (String s : strs) {
// Replace each occurrence of '/' with '//'
// This is our way of "escaping" the slash character
// Then add our delimiter '/:' to the end
encodedString.append(s.replace("/", "//")).append("/:");
}
// Return the final encoded string
return encodedString.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode_3(String s) {
// Initialize a List to hold the decoded strings
List<String> decodedStrings = new ArrayList<>();
// Initialize a StringBuilder to hold the current string being built
StringBuilder currentString = new StringBuilder();
// Initialize an index 'i' to start of the string
int i = 0;
// Iterate while 'i' is less than the length of the encoded string
while (i < s.length()) {
// If we encounter the delimiter '/:'
if (i + 1 < s.length() && s.charAt(i) == '/' && s.charAt(i + 1) == ':') {
// Add the currentString to the list of decodedStrings
decodedStrings.add(currentString.toString());
// Clear currentString for the next string
currentString = new StringBuilder();
// Move the index 2 steps forward to skip the delimiter
i += 2;
}
// If we encounter an escaped slash '//'
else if (i + 1 < s.length() && s.charAt(i) == '/' && s.charAt(i + 1) == '/') {
// Add a single slash to the currentString
currentString.append('/');
// Move the index 2 steps forward to skip the escaped slash
i += 2;
}
// Otherwise, just add the character to currentString and move the index 1 step forward.
else {
currentString.append(s.charAt(i));
i++;
}
}
// Return the list of decoded strings
return decodedStrings;
}
// V3
// IDEA : Chunked Transfer Encoding
// https://leetcode.com/problems/encode-and-decode-strings/editorial/
public String encode_4(List<String> strs) {
// Initialize a StringBuilder to hold the encoded string.
StringBuilder encodedString = new StringBuilder();
for (String s : strs) {
// Append the length, the delimiter, and the string itself.
encodedString.append(s.length()).append("/:").append(s);
}
return encodedString.toString();
}
public List<String> decode_4(String s) {
// Initialize a list to hold the decoded strings.
List<String> decodedStrings = new ArrayList<>();
int i = 0;
while (i < s.length()) {
// Find the delimiter.
int delim = s.indexOf("/:", i);
// Get the length, which is before the delimiter.
int length = Integer.parseInt(s.substring(i, delim));
// Get the string, which is of 'length' length after the delimiter.
String str = s.substring(delim + 2, delim + 2 + length);
// Add the string to the list.
decodedStrings.add(str);
// Move the index to the start of the next length.
i = delim + 2 + length;
}
return decodedStrings;
}
// V4
// https://leetcode.ca/2016-08-27-271-Encode-and-Decode-Strings/
public class Codec {
// Encodes a list of strings to a single string.
public String encode(List<String> strs) {
StringBuilder ans = new StringBuilder();
for (String s : strs) {
ans.append((char) s.length()).append(s);
}
return ans.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode(String s) {
List<String> ans = new ArrayList<>();
int i = 0, n = s.length();
while (i < n) {
int size = s.charAt(i++);
ans.add(s.substring(i, i + size));
i += size;
}
return ans;
}
}
}