-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_length_encoding.h
More file actions
65 lines (54 loc) · 1.5 KB
/
Copy pathrun_length_encoding.h
File metadata and controls
65 lines (54 loc) · 1.5 KB
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
#ifndef CPP_ALGORITHM_RUN_LENGTH_ENCODING_H
#define CPP_ALGORITHM_RUN_LENGTH_ENCODING_H
#include <string>
namespace RunLengthEncoding
{
/**
* \brief Run-length encoding is a form of data compression,
* where runs are replaced by just one data value and count.
* \param str raw string
* \return compressed string
*/
std::string RunLengthEncoding(const std::string& str);
/**
* \brief Run-length decoding is the reverse of run-length encoding.
* \param str compressed string
* \return raw string
*/
std::string RunLengthDecoding(const std::string& str);
}
// ----------------------------------------------------------------------------
inline std::string RunLengthEncoding::RunLengthEncoding(const std::string& str)
{
int count = 0;
std::string result;
for (int i = 0; i < static_cast<int>(str.size()); ++i)
{
++count;
if (i + 1 == static_cast<int>(str.size()) || str[i] != str[i + 1])
{
result += std::to_string(count) + str[i];
count = 0;
}
}
return result;
}
// ----------------------------------------------------------------------------
inline std::string RunLengthEncoding::RunLengthDecoding(const std::string& str)
{
int count = 0;
std::string result;
for (const char& c : str)
{
if (std::isdigit(c))
{
count = c - '0';
}
else
{
result.append(count, c);
}
}
return result;
}
#endif