LeetCode 271: Encode and Decode Strings

ArrayStringDesign

Problem Description

Explanation:

To encode and decode a list of strings, we can use a delimiter to separate each string when encoding. During encoding, we concatenate all the strings with a delimiter in between. During decoding, we split the encoded string using the delimiter to retrieve the original list of strings.

Encoding:

  1. Concatenate all strings in the input list with a delimiter in between.
  2. Return the concatenated string.

Decoding:

  1. Split the encoded string using the delimiter.
  2. Return the list of strings.

Time Complexity:

  • Encoding: O(n), where n is the total number of characters in all strings.
  • Decoding: O(n), where n is the length of the encoded string.

Space Complexity:

  • Encoding: O(n), where n is the total number of characters in all strings.
  • Decoding: O(n), where n is the length of the encoded string.

Solutions

public class Codec {

    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        return String.join("#", strs);
    }

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        return Arrays.asList(s.split("#"));
    }
}

Loading editor...