|
4 | 4 | import java.util.List;
|
5 | 5 |
|
6 | 6 | /**
|
7 |
| - * 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. |
| 7 | + * 271. Encode and Decode Strings |
| 8 | + * |
| 9 | + * Design an algorithm to encode a list of strings to a string. |
| 10 | + * The encoded string is then sent over the network and is decoded back to the original list of strings. |
8 | 11 |
|
9 | 12 | Machine 1 (sender) has the function:
|
10 | 13 |
|
@@ -33,25 +36,27 @@ vector<string> decode(string s) {
|
33 | 36 | Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.
|
34 | 37 | */
|
35 | 38 | public class _271 {
|
36 |
| - // Encodes a list of strings to a single string. |
37 |
| - public String encode(List<String> strs) { |
38 |
| - StringBuilder sb = new StringBuilder(); |
39 |
| - for (String s : strs) { |
40 |
| - sb.append(s.length()).append('/').append(s); |
| 39 | + public static class Solution1 { |
| 40 | + // Encodes a list of strings to a single string. |
| 41 | + public String encode(List<String> strs) { |
| 42 | + StringBuilder sb = new StringBuilder(); |
| 43 | + for (String s : strs) { |
| 44 | + sb.append(s.length()).append('/').append(s); |
| 45 | + } |
| 46 | + return sb.toString(); |
41 | 47 | }
|
42 |
| - return sb.toString(); |
43 |
| - } |
44 | 48 |
|
45 |
| - // Decodes a single string to a list of strings. |
46 |
| - public List<String> decode(String s) { |
47 |
| - List<String> result = new ArrayList<String>(); |
48 |
| - int i = 0; |
49 |
| - while (i < s.length()) { |
50 |
| - int slash = s.indexOf('/', i); |
51 |
| - int size = Integer.valueOf(s.substring(i, slash)); |
52 |
| - result.add(s.substring(slash + 1, slash + 1 + size)); |
53 |
| - i = slash + size + 1; |
| 49 | + // Decodes a single string to a list of strings. |
| 50 | + public List<String> decode(String s) { |
| 51 | + List<String> result = new ArrayList<>(); |
| 52 | + int i = 0; |
| 53 | + while (i < s.length()) { |
| 54 | + int slash = s.indexOf('/', i); |
| 55 | + int size = Integer.valueOf(s.substring(i, slash)); |
| 56 | + result.add(s.substring(slash + 1, slash + 1 + size)); |
| 57 | + i = slash + size + 1; |
| 58 | + } |
| 59 | + return result; |
54 | 60 | }
|
55 |
| - return result; |
56 | 61 | }
|
57 | 62 | }
|
0 commit comments