-
Notifications
You must be signed in to change notification settings - Fork 0
/
StringCompression.cpp
63 lines (52 loc) · 1.41 KB
/
StringCompression.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//
// Created by Amit on 11/23/2016.
//
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_RLEN 50
/* Returns the Run Length Encoded string for the
source string src */
char *encode(char *src)
{
int rLen;
char count[MAX_RLEN];
int len = strlen(src);
/* If all characters in the source string are different,
then size of destination string would be twice of input string.
For example if the src is "abcd", then dest would be "a1b1c1d1"
For other inputs, size would be less than twice. */
char *dest = (char *)malloc(sizeof(char)*(len*2 + 1));
int i, j = 0, k;
/* traverse the input string one by one */
for(i = 0; i < len; i++)
{
/* Copy the first occurrence of the new character */
dest[j++] = src[i];
/* Count the number of occurrences of the new character */
rLen = 1;
while(i + 1 < len && src[i] == src[i+1])
{
rLen++;
i++;
}
/* Store rLen in a character array count[] */
sprintf(count, "%d", rLen);
/* Copy the count[] to destination */
for(k = 0; *(count+k); k++, j++)
{
dest[j] = count[k];
}
}
/*terminate the destination string */
dest[j] = '\0';
return dest;
}
/*driver program to test above function dfgdf */
int main()
{
char str[] = "aaabbbbbccc";
char *res = encode(str);
cout<<"hi";
printf("%s", res);
}