Given a string eg "aaabbccaaadd" replace the same string as "3a2b2c2a2d" .....
Microsoft Interview Questions and Answers
(Continued from previous question...)
80. Given a string eg "aaabbccaaadd" replace the same string as "3a2b2c2a2d" .....
Question:
Given a string eg "aaabbccaaadd" replace the same string as "3a2b2c2a2d". Will you logic work given the compressed string and back to the original string?
maybe an answer:
public static string DeCompress(string word)
{
//3a2b2c3a2d
var warray = word.ToCharArray();
int count = 0;
StringBuilder number = new StringBuilder();
StringBuilder result = new StringBuilder();
for (int i = 0; i < warray.Length; i++ )
{
if(char.IsDigit(warray[i]))
{
number.Append(warray[i].ToString());
}else
{
int amount = int.Parse(number.ToString());
for(int j = 0; j< amount; j++)
{
result.Append(warray[i].ToString());
}
number.Clear();
}
}
return result.ToString();
}
public static string Compress(string word)
{
var warray = word.ToCharArray();
StringBuilder sb = new StringBuilder();
char current = warray[0];
char previous;
int count = 0;
foreach (var ch in warray)
{
if (current == ch)
{
count++;
}
else
{
previous = current;
sb.Append(count + "" + previous.ToString());
count = 0;
current = ch;
count++;
}
}
sb.Append(count + "" + current.ToString());
return sb.ToString();
}
(Continued on next question...)
Other Interview Questions
|