LeetCode Solutions

271. Encode and Decode Strings

Time: $O(n)$

Space: $O(n)$

			

class Codec {
 public:
  // Encodes a list of strings to a single string.
  string encode(vector<string>& strs) {
    string encoded;

    for (const string& s : strs)
      encoded += to_string(s.length()) + '/' + s;

    return encoded;
  }

  // Decodes a single string to a list of strings.
  vector<string> decode(string s) {
    vector<string> decoded;

    for (int i = 0; i < s.length();) {
      const int slash = s.find('/', i);
      const int length = stoi(s.substr(i, slash - i));
      i = slash + length + 1;
      decoded.push_back(s.substr(slash + 1, i - slash - 1));
    }

    return decoded;
  }
};
			

public class Codec {
  // Encodes a list of strings to a single string.
  public String encode(List<String> strs) {
    StringBuilder encoded = new StringBuilder();

    for (final String s : strs)
      encoded.append(s.length()).append('/').append(s);

    return encoded.toString();
  }

  // Decodes a single string to a list of strings.
  public List<String> decode(String s) {
    List<String> decoded = new ArrayList<>();

    for (int i = 0; i < s.length();) {
      final int slash = s.indexOf('/', i);
      final int length = Integer.parseInt(s.substring(i, slash));
      i = slash + length + 1;
      decoded.add(s.substring(slash + 1, i));
    }

    return decoded;
  }
}
			

class Codec:
  def encode(self, strs: List[str]) -> str:
    """Encodes a list of strings to a single string."""
    return ''.join(str(len(s)) + '/' + s for s in strs)

  def decode(self, s: str) -> List[str]:
    """Decodes a single to a list of strings."""
    decoded = []

    i = 0
    while i < len(s):
      slash = s.find('/', i)
      length = int(s[i:slash])
      i = slash + length + 1
      decoded.append(s[slash + 1:i])

    return decoded