Skip to main content

Encode and Decode Strings

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 156 ms)​

MetricValue
Runtime156 ms
Memory46.7 MB
Date2021-12-18
Solution
public class Codec {

// Encodes a list of strings to a single string.
public string encode(IList<string> strs)
{
StringBuilder sb = new StringBuilder();
foreach (var str in strs)
{
sb.Append($"{str.Length}/{str}");
}
return sb.ToString();
}

// Decodes a single string to a list of strings.
public IList<string> decode(string s)
{
List<string> result = new List<string>();
int i = 0;
while (i < s.Length)
{
int slash = s.IndexOf('/', i);
int size = Convert.ToInt32(s.Substring(i, slash - i));
i = slash + size + 1;
result.Add(s.Substring(slash + 1, size));
}
return result;
}
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed