Skip to content

271. Encode and Decode Strings

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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 string 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