Encode and Decode Strings
Problem Information
- Leetcode problem: https://leetcode.com/problems/encode-and-decode-strings/
- Neetcode problem: https://neetcode.io/problems/string-encode-and-decode
- Difficulty: Medium
Solution
We encode the strings in the following format:
["neet", "code", "love", "you"] -> 4#neet4#code4#love#3you.
- Time Complexity
O(n)where n is the number of strings - Space Complexity
O(n)
public class Solution {
public String encode(List<String> strs) {
if (strs.isEmpty())
return "";
StringBuilder res = new StringBuilder();
List<Integer> sizes = new ArrayList<>();
for (String str : strs) {
sizes.add(str.length());
}
for (int size : sizes) {
res.append(size).append(',');
}
res.append('#');
for (String str : strs) {
res.append(str);
}
return res.toString();
}
public List<String> decode(String str) {
if (str.length() == 0)
return new ArrayList<>();
List<String> res = new ArrayList<>();
List<Integer> sizes = new ArrayList<>();
int i = 0;
while (str.charAt(i) != '#') {
StringBuilder cur = new StringBuilder();
while (str.charAt(i) != ',') {
cur.append(str.charAt(i));
i++;
}
sizes.add(Integer.parseInt(cur.toString()));
i++;
}
i++;
for (int sz : sizes) {
res.add(str.substring(i, i + sz));
i += sz;
}
return res;
}
}