-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompressString.cpp
75 lines (57 loc) · 1.3 KB
/
CompressString.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
64
65
66
67
68
69
70
71
72
73
74
75
//
// main.cpp
// InterviewPrep
//
// Created by Clifton Gordon on 11/24/15.
// Copyright © 2015 Clifton Gordon. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
int RunLength(char **s)
{
if (!s || !(*s) || !(*s)[0])
return 0;
// Makes things easier to read...
char *c = *s;
int runLen = 1;
char match = *c;
while (*(++c) == match)
runLen++;
// Caller needs us to update the reader
*s = c;
return runLen;
}
void CompressString(char *s)
{
if (!s || !s[0])
return;
char *reader = s;
int len = RunLength(&reader);
while(len > 0)
{
s++;
if (len > 1)
{
// For this example, we won't bother with runs greater than 9
*s = len + '0';
s++;
}
*s = *reader;
len = RunLength(&reader);
}
}
void RunTest(char *s1)
{
char buffer[1024] = {};
strcpy(buffer, s1);
printf("before: %s\n", buffer);
CompressString(buffer);
printf("after: %s\n", buffer);
}
int main(int argc, const char * argv[]) {
RunTest("aabcccccaaa");
RunTest("abksjdjdjsieeekeelslkslsssjejifiiiiidijsiisisissssslslslslllllllleieiiieeeuuee");
RunTest("abiejslenw");
return 0;
}