-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest-balanced-substring-2.cpp
More file actions
97 lines (90 loc) · 2.06 KB
/
longest-balanced-substring-2.cpp
File metadata and controls
97 lines (90 loc) · 2.06 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
87
88
89
90
91
92
93
94
95
96
97
// https://leetcode.com/problems/longest-balanced-substring-ii/
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int ans = 0;
void checkSingle(string &s)
{
int n = s.size();
int i = 0;
while (i < n)
{
int j = i;
while (j < n && s[i] == s[j])
j++;
ans = max(ans, j - i);
i = j;
}
}
void checkDouble(string &s, char x, char y, char skip)
{
int n = s.size();
unordered_map<int, int> lastSeen;
int cnt = 0;
lastSeen[0] = -1;
for (int i = 0; i < n; i++)
{
if (s[i] == skip)
{
cnt = 0;
lastSeen.clear();
lastSeen[0] = i;
continue;
}
cnt += (s[i] == x ? 1 : -1);
if (lastSeen.count(cnt))
{
ans = max(ans, i - lastSeen[cnt]);
}
else
{
lastSeen[cnt] = i;
}
}
}
void checkTriple(string &s)
{
int n = s.size();
int cntA = 0;
int cntB = 0;
int cntC = 0;
map<pair<int, int>, int> mp;
mp[{0, 0}] = -1;
for (int i = 0; i < n; i++)
{
if (s[i] == 'a')
cntA++;
else if (s[i] == 'b')
cntB++;
else
cntC++;
int ab = cntA - cntB;
int ac = cntA - cntC;
pair<int, int> p = {ab, ac};
if (mp.count(p))
{
ans = max(ans, i - mp[p]);
}
else
mp[p] = i;
}
}
int longestBalanced(string s)
{
checkSingle(s);
checkDouble(s, 'a', 'b', 'c');
checkDouble(s, 'a', 'c', 'b');
checkDouble(s, 'b', 'c', 'a');
checkTriple(s);
return ans;
}
};
int main()
{
Solution sol;
string s = "abcabc";
cout << sol.longestBalanced(s) << endl; // Output: 6
return 0;
}