Advertisement
lifeiteng

271. Encode and Decode Strings

Sep 12th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.97 KB | None | 0 0
  1. public class Codec {
  2.  
  3.     // Encodes a list of strings to a single string.
  4.     public String encode(List<String> strs) {
  5.         StringBuilder sb = new StringBuilder();
  6.         for(String str : strs)
  7.         {
  8.             sb.append(str.length()+"#");
  9.             sb.append(str);
  10.         }
  11.         return sb.toString();
  12.     }
  13.  
  14.     // Decodes a single string to a list of strings.
  15.     public List<String> decode(String s) {
  16.         List<String> list = new ArrayList<>();
  17.         while(s.length() > 0)
  18.         {
  19.             int k = 0, i = 0;
  20.             while('0' <= s.charAt(i) && s.charAt(i) <= '9')
  21.             {
  22.                 k = k * 10 + s.charAt(i) - '0';
  23.                 i++;
  24.             }
  25.             list.add(s.substring(i + 1, i + 1 + k));
  26.             s = s.substring(i + 1 + k);
  27.         }
  28.         return list;
  29.     }
  30. }
  31.  
  32. // Your Codec object will be instantiated and called as such:
  33. // Codec codec = new Codec();
  34. // codec.decode(codec.encode(strs));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement