Interview Question
Country: India
Here my solution using Scala :)
def compress(str:Seq[Char]):String = {
str.headOption match {
case Some(headChar) => {
str.takeWhile {_ == headChar}.size match {
case justOne if (justOne == 1) => headChar + compress(str.tail)
case digit => (headChar + digit.toString) + compress(str.drop(digit))
}
}
case None => str.toString
}
}
Code written in C:
char* runLengthEncoding(char* src, int len){
if(!src) return NULL;
char currentChar = src[0];
int charCount = 1;
int pivIndex = 0;
for(int i=1; i<len; i++){
if(src[i]!=currentChar){
src[pivIndex++] = currentChar;
if(charCount > 1)
src[pivIndex++] = charCount;
currentChar = src[i]; charCount = 1;
}
else
charCount++;
}
src[pivIndex] = '\0';
return src;
}
string convertString(string input)
{
string toReturn;
char tmp;
int count = 0;
string::iterator itr = input.begin();
for(;itr != input.end();)
{
if(isalpha(*itr))
{
toReturn.append(1,*itr);
tmp = *itr;
count = 1;
itr++;
while(tmp = = *itr)
{
count++;
itr++;
}
toReturn.append(count);//convert count to string....
}
else
{
toReturn.append(1,*itr);
itr++
}
}
return toReturn;
}
-- Working Code;
- Shekar Gurram February 16, 2012-- Written in C#;