Repository navigation
Expand file tree
/
Copy pathQ15-compressStr.cpp
More file actions
86 lines (79 loc) · 1.51 KB
/
Copy pathQ15-compressStr.cpp
File metadata and controls
86 lines (79 loc) · 1.51 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// Q115-compressStr.cpp
// Algorithm-Linux
//
// Created by SanQ11iang Zhao on 12/4/12.
// Copyright (c) 2012 SanQ11iang Zhao. All rights reserved.
//
/*
std::cout<<compressStr("aaabbccddeeeee")<<std::endl;
std::cout<<compressStr("amp")<<std::endl;
*/
#include "Q15-compressStr.h"
char * compressStr(char *str)
{
int length = getLength(str),i;
if (length>strlen(str)) {
return str;
}
char *result = new char[length];
char *runner =result;
++str;
int num = 1;
while (*str) {
if (*str == *(str-1)) {
++num;
}else
{
concat(runner, (str-1), num);
num =1;
}
++str;
}
if (num>0) {
concat(runner, (str-1), num);
}
*runner='\0';
return result;
}
int getLength(char *str)
{
char * runner = str;
++runner;
int num_length = 1,length =0;
while (*runner) {
if (*runner == *(runner-1)) {
++num_length;
}else
{
length+=1+getDigit(num_length);
num_length =0;
}
++runner;
}
if (num_length>0) {
length += 1+getDigit(num_length);
}
return length;
}
int getDigit(int num)
{
int length = 0;
while (num >0) {
++length;
num = num / 10;
}
if (length == 0) {
return 1;
}
return length;
}
void concat(char * &str, char *ch, int num)
{
*str= *ch; ++str;
while (num>0) {
*str = '0' + num % 10;
num /= 10;
++str;
}
}