Interview Question
Country: India
Here is something I quickly cooked up.. I'm pretty sure this question has been posted before somewhere in this forum
public static String compressString(String inputStr) {
if (inputStr.length() < 2)
return inputStr;
int currentCnt = 0;
StringBuffer compressedStr = new StringBuffer();
char[] charArr = inputStr.toCharArray();
char currentChar = charArr[0];
for (int i = 0; i < charArr.length; i++) {
char c = charArr[i];
if (c != currentChar) {
compressedStr.append(currentChar);
compressedStr.append(currentCnt);
if (compressedStr.length() >= inputStr.length())
return inputStr;
currentCnt = 1;
currentChar = c;
} else {
currentCnt++;
}
}
compressedStr.append(currentChar);
compressedStr.append(currentCnt);
return (compressedStr.length() >= inputStr.length()? inputStr: compressedStr.toString());
}
Check this one; Written in C#;
static void Main(string[] args)
{
int index = 0;
Char[] str = { 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'd', 'd', 'e', 'e', 'e', 'r', 't' };
char currentChar;
int count;
for (int i = 0; i < str.Length; )
{
currentChar = str[i];
count = 1;
int j = i + 1;
while (j < str.Length && str[i] == str[j])
{
count++; j++;
}
str[index] = str[i];
Console.Write(str[index]); // To print the character on to console;
if (count > 1)
{
str[index + 1] = Char.Parse(count.ToString());
Console.Write(str[index + 1]); // To print the number of occurrences;
}
Console.WriteLine(); // To print a new line;
index += count;
i += count;
}
}
#include <stdio.h>
#include <string.h>
#define A 'a'
#define B 'b'
#define C 'c'
void compress(char c[], int l) {
printf("compress : %d, %s\n", l, c);
int i=0;
int sum=0, rem=0, avg;
for (i=0;i<l;i++) sum += c[i];
rem = sum % l;
avg = sum / l;
//check if all elements are same
if((avg==A && !rem) || (avg==B && !rem) || (avg==C && !rem)) return;
if(l==2) {
c[0]=A+B+C-c[0]-c[1];
c[1]='\0';
return;
}else{
while((i+2)<l) {
printf("compress1 : %d, %s\n", l, c);
if((c[i+0]+c[i+1]+c[i+2])==(A+B+C)) {
if(c[i+3]!=c[i+2])
c[i+0]=c[i+2];
else
c[i+0]=c[i+1];
memmove(&c[i+1], &c[i+2], l-i);
c[l]='\0'; --l;
continue;
}
i++;
}
printf("i, l : %d, %d\n", i, l);
i=0;
while((i+1)<l) {
printf("compress2 : %d, %s\n", l, c);
if(((c[i+0]+c[i+1])==(A+B))|| ((c[i+0]+c[i+1])==(B+C)) || ((c[i+0]+c[i+1])==(A+C))){
c[i+0]=A+B+C-c[i+0]-c[i+1];
memmove(&c[i+1], &c[i+2], l-i);
c[l]='\0'; --l;
continue;
}
i++;
if(i==l && l>2)
i=0;
}
printf("**i, l : %d, %d\n", i, l);
//if(i==l)
// return;
compress(c,l);
}
}
int main(void) {
int i, len;
char c[40];
printf("Enter string {a,b,c}* : ");
scanf("%s",c);
len=strlen(c);
printf("String is : %s\n",c);
compress(c,len);
printf("String is : %s\n",c);
return 0;
}
What you are trying to do here. Compressing means what? give your input and output.
- Sidhartha February 15, 2012