File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed
Hash/3714.Longest-Balanced-Substring-II Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int longestBalanced (string s) {
4+ int n = s.size ();
5+ int best = 0 ;
6+
7+ int run = 1 ;
8+ for (int i=1 ; i<n; i++) {
9+ if (s[i]==s[i-1 ])
10+ run++;
11+ else {
12+ best = max (best, run);
13+ run = 1 ;
14+ }
15+ }
16+ best = max (best, run);
17+
18+ for (char skip: {' a' ,' b' ,' c' }) {
19+ int i = 0 ;
20+ while (i<n) {
21+ while (i<n && s[i]==skip) i++;
22+ if (i>=n) break ;
23+ int j = i;
24+ while (j<n && s[j]!=skip) j++;
25+
26+ if (j-i>=2 ) {
27+ unordered_map<int ,int >first;
28+ first[0 ] = i-1 ;
29+ int diff = 0 ;
30+ char c1 = s[i];
31+ for (int k=i; k<j; k++) {
32+ if (s[k]==c1) diff++;
33+ else diff--;
34+ if (first.find (diff)!=first.end ()) {
35+ int len = k-first[diff];
36+ best = max (best, len);
37+ } else {
38+ first[diff] = k;
39+ }
40+ }
41+ }
42+ i = j;
43+ }
44+ }
45+
46+ map<pair<int ,int >, int >Map;
47+ Map[{0 ,0 }] = -1 ;
48+ int ca=0 , cb=0 , cc=0 ;
49+ for (int i=0 ; i<n; i++) {
50+ if (s[i]==' a' ) ca++;
51+ else if (s[i]==' b' ) cb++;
52+ else cc++;
53+ if (Map.find ({ca-cb, ca-cc})!=Map.end ()) {
54+ int len = i - Map[{ca-cb,ca-cc}];
55+ best = max (best, len);
56+ } else {
57+ Map[{ca-cb,ca-cc}] = i;
58+ }
59+ }
60+
61+ return best;
62+ }
63+ };
You can’t perform that action at this time.
0 commit comments