Google Interview Question
Software Engineer InternsCountry: United States
def encode(strings):
result = ''
count = str(len(strings))
result += count + '|'
for s in strings:
result += str(len(s)) + '|' + s
return result
def decode(s):
index = s.find('|')
count = int(s[:index])
result = []
s = s[index + 1:]
for i in range(count):
index = s.find('|')
count = int(s[:index])
s = s[index + 1:]
result.append(s[:count])
s = s[count:]
return result
def encode(strings):
result = ''
count = str(len(strings))
result += count + '|'
for s in strings:
result += str(len(s)) + '|' + s
return result
def decode(s):
index = s.find('|')
count = int(s[:index])
result = []
s = s[index + 1:]
for i in range(count):
index = s.find('|')
count = int(s[:index])
s = s[index + 1:]
result.append(s[:count])
s = s[count:]
return result
in C#
string encode(List<string> input)
{
// the string will be like "{ word1, word 2, word3, word4, word5 }"
string s = input.ToLogString();
//remove "{" and "}"
s = s.Substring(1, s.Length - 2);
return s.Trim();
}
List<string> decode(string input)
{
//input="word1, word 2, word3, word4, word5"
List<string> list=new List<string>();
if (string.IsNullOrEmpty(input))
return list;
int i = input.IndexOf(",");
while (i > 0)
{
string temp=input.Substring(0,i);
list.Add(temp.Trim());
input = input.Substring(i+1);
i = input.IndexOf(",");
}
list.Add(input.Trim());
return list;
}
- MT October 30, 2014