Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Encode function
- Time Complexity: O(Number of strings in the list)
- Space Complexity: O(Sum of length of all strings in the list)
- Decode function
- Time Complexity: O(Length of the string)
- Space Complexity: O(1)
- */
- public class Codec {
- // Encodes a list of strings to a single string.
- public String encode(List<String> strs) {
- if (strs == null || strs.size() == 0) {
- return "";
- }
- StringBuilder sb = new StringBuilder();
- for (String str : strs) {
- sb.append(str.length());
- sb.append("/");
- sb.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();
- if (s == null || s.length() == 0) {
- return result;
- }
- int i = 0;
- while (i < s.length()) {
- int slashIndex = s.indexOf("/", i);
- int strLength = Integer.valueOf(s.substring(i, slashIndex));
- result.add(s.substring(slashIndex+1, slashIndex+strLength+1));
- i = slashIndex+strLength+1;
- }
- return result;
- }
- }
- // Your Codec object will be instantiated and called as such:
- // Codec codec = new Codec();
- // codec.decode(codec.encode(strs));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement