-
Notifications
You must be signed in to change notification settings - Fork 160
/
Chars with maximal number of consecutive counts.cpp
122 lines (87 loc) · 2.29 KB
/
Chars with maximal number of consecutive counts.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
Given a string, print out the chars with maximal number of consecutive counts
For example:
Input: "this is a sentence"
Output: [t, h, i, s, i, s, a, s, e, n, t, e, n, c, e]
Input: "thiisss iss a senntttenceee"
Output: [s, t, e]
Input:"thiisss iss a sennnntttenceee"
Output: [n]
*/
#include<iostream>
#include<string>
using namespace std;
/*
solution1: whenever the two different consecutive chars occur, update the count and final result
if the count is equal to larger than current maximal count, otherwise, just reset the count.
*/
void MaxRepCount1(char *sen) {
if (!sen || !(*sen)) return;
int maxcount = 0;
int curcount = 0;
string result;
char prechar = *sen;
do {
if (*sen!=prechar) {
if(curcount >= maxcount && isalpha(prechar)) {
if (curcount> maxcount) result.clear();
result += prechar;
maxcount = curcount;
}
prechar=*sen;
curcount=1;
} else {
count++;
}
} while(*sen++);
cout<<result<<endl;
}
/*
solution2: scan the array to find the maximal count, scan again to output the chars with maximal count.
O(n) time, O(1) space
*/
void MaxRepCount2(char *sen) {
if (!sen || !(*sen)) return;
int table[256] = {0};
char *p = sen;
int maxcount = 1;
int curcount = 1;
int index = 0;
char c = *p;
// first pass to count and find max
while (*p) {
c = *p;
curcount = 0;
while (*p == c) {
curcount++;
p++;
index++;
}
if (curcount >= maxcount) {
maxcount = curcount;
table[index-1] = curcount;
}
}
// second pass to output each max alphabet only once
p = sen;
index = 0;
cout<<"[";
while (*p) {
c = *p;
if ((table[index] == max) && (isalpha(c))) {
cout<<c<<",";
}
p++;
index++;
}
cout<<"]"<<endl;
}
int main() {
//char s[] = "this is a sentence";
//char s[] = "thiis iss a senntencee";
char s[] = "thiisss iss a senntttenceee";
//char s[] = "thiisss iss a sennnntttenceee";
MaxRepCount1(s);
MaxRepCount2(s);
return 0;
}