Compress the String
Write a program to do basic string compression. For a character which is consecutively repeated more than once, replace consecutive duplicate occurrences with the count of repetitions.
Exmple:
Note :
Input Format:
Output Format:
Note:
Constraints:
Sample Input 1:
Sample Output 1:
Sample Input 2:
Sample Output 2:
#include <iostream>
#include <cstring>
using namespace std;
#include "solution.h"
void stringCompression(char myStr[]){
char *s = myStr;
char *r, *p;
int count, i;
while (*s)
{
/*initially only 1 character of a kind is present*/
count = 1;
/*we check whether current character matches the next one*/
while (*s && *s == *(s+1))
{
/*if yes,then increase the count due to the match
and increment the string pointer to next */
count++;
s++;
}
if (count > 1) /*if more than one character of a kind is present*/
{
/*assign the value of count to second occurence of a particular character*/
*(s - count + 2) = count + '0';
/*delete all other occurences except the first one and second one using array shift*/
for (i = 0; i < count - 2; i++)
{
p = s + 1;
r = s;
while (*r)
*r++ = *p++;
s--;
}
}
s++;
}
}
int main() {
int size = 1e6;
char str[size];
cin >> str;
stringCompression(str);
cout << str;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
void stringCompression(char str[]){
int n = strlen(str);
char temp[100];
int k=0;
int i;
for ( i = 0; i < n; i++) {
// Count occurrences of current character
int count = 1;
while (i < n - 1 && str[i] == str[i + 1]) {
count++;
i++;
}
// Print character and its count
temp[k]=str[i];
k++;
if(count!=1){
temp[k]=48+count;
k++;
}
}
for(int i=0;i<=k;i++){
str[i]=temp[i];
}
str[k]='\0';
}
Comments
Post a Comment