Interview Question
SDE1sCountry: India
First there is no boundry defined in your question, so i did not consider that.
Second - as per the question, we are going to compress the string. It is a common requirement in business senarios. So for that if size of a character is 1 we did not make any change that.
@Ajeet: I don't think you see the flaws in your code
- (int) 1 # (char) '1'
- (int) 10 -> string '10' and for that P1 need to increase 2
with the assumption that we need to answer an interview question so at least you need to give some kinds of working code. Pseudo code has no longer been accepted in the interview
This is easy problem however it is the kind of question to see how careful your coding is.
One thing to note is the count need to be converted to string before we write, and the count might have several digits
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void reptonum(char* s, int n) {
char *rp, *wp;
rp = wp = s;
if (n <= 1) return;
while (rp < s + n) {
char cur = *rp;
int cnt = 0;
while (*rp == cur && rp < s + n) {
++rp;
++cnt;
}
*wp++ = cur;
if (cnt > 1) {
ostringstream convert;
convert << cnt;
string nums = convert.str();
for (int i=0; i< nums.length(); ++i) {
*wp++ = nums[i];
}
}
}
*wp = 0;
cout << s << endl;
}
int main()
{
char s[] = "AAAABCDDD";
reptonum(s, sizeof(s) / sizeof(s[0]));
char s1[] = "AAAAAAAAAAAAAAABCCD";
reptonum(s1, sizeof(s1) / sizeof(s1[0]));
char s2[] = "ABCD";
reptonum(s2, sizeof(s2) / sizeof(s2[0]));
}
#include<stdio.h>
#include<string.h>
int main()
{
char arr[11]="AAAABCCDDD";
int i,index=0,count=0;
for(i=0;i<11;i++)
{
if(arr[index]==arr[i])
{
count++;
}
if(arr[index]!=arr[i] )
{
if(count==1)
{
printf("%c",arr[i-1]);
index=i;
count=0;
--i;
}
else
{
printf("%c%d",arr[i-1],count);
index=i;
count=0;
--i;
}
}
}
}
This can be achieved in Java, with simple code like this -
public class AlphabetCount {
public static void main(String[] args) {
String str = "AAAABCCDDD";
//String str = "ABCD";
//String str = "AAAA";
//String str = "";
StringBuffer sb = new StringBuffer(str), sbTarget = new StringBuffer();
char prevChar = ' ', currentChar = ' ';
int prevCharCount = 0;
for(int i=0, len=sb.length(); i<len; i++)
{
currentChar = sb.charAt(i);
if(currentChar != prevChar)
{
if(prevCharCount > 1)
sbTarget.append(prevCharCount);
sbTarget.append(currentChar);
prevCharCount = 1;
prevChar = currentChar;
}
else
prevCharCount++;
}
if(prevCharCount > 1)
sbTarget.append(prevCharCount);
System.out.println(sbTarget);
}
}
An efficient solution in c code
#include<stdio.h>
#include<conio.h>
void main()
{
char a[20];
static int i,j,n;
printf("Enter the string:");
gets(a);
for(i=0;;)
{
for(j=i;a[j]==a[i];j++)
{
n++;
}
if(n>1)
printf("%c%d",a[i],n);
else
printf("%c",a[i]);
n=0;
i=j;
if(a[i]=='\0')
break;
}
getch();
}
}
Modified to working java code ... still i prefer pseudocode ... :)
- Ajeet October 10, 2013