Advertisement
1988coder

271. Encode and Decode Strings

Nov 27th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. /*
  2. Encode function
  3. Time Complexity: O(Number of strings in the list)
  4. Space Complexity: O(Sum of length of all strings in the list)
  5.  
  6. Decode function
  7. Time Complexity: O(Length of the string)
  8. Space Complexity: O(1)
  9. */
  10. public class Codec {
  11.  
  12.     // Encodes a list of strings to a single string.
  13.     public String encode(List<String> strs) {
  14.         if (strs == null || strs.size() == 0) {
  15.             return "";
  16.         }
  17.         StringBuilder sb = new StringBuilder();
  18.         for (String str : strs) {
  19.             sb.append(str.length());
  20.             sb.append("/");
  21.             sb.append(str);
  22.         }
  23.         return sb.toString();
  24.     }
  25.  
  26.     // Decodes a single string to a list of strings.
  27.     public List<String> decode(String s) {
  28.         List<String> result = new ArrayList();
  29.         if (s == null || s.length() == 0) {
  30.             return result;
  31.         }
  32.         int i = 0;
  33.         while (i < s.length()) {
  34.             int slashIndex = s.indexOf("/", i);
  35.             int strLength = Integer.valueOf(s.substring(i, slashIndex));
  36.             result.add(s.substring(slashIndex+1, slashIndex+strLength+1));
  37.             i = slashIndex+strLength+1;
  38.         }
  39.         return result;
  40.     }
  41. }
  42.  
  43. // Your Codec object will be instantiated and called as such:
  44. // Codec codec = new Codec();
  45. // codec.decode(codec.encode(strs));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement