-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathlongest-balanced-substring-i.cpp
More file actions
45 lines (43 loc) · 1.19 KB
/
longest-balanced-substring-i.cpp
File metadata and controls
45 lines (43 loc) · 1.19 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
// Time: O(n * (26 + n))
// Space: O(26)
// freq table
class Solution {
public:
int longestBalanced(string s) {
int result = 0;
for (int i = 0; i < size(s); ++i) {
vector<int> cnt(26);
int mx = 0, unique = 0;
for (int j = i; j < size(s); ++j) {
if (++cnt[s[j] - 'a'] == 1) {
++unique;
}
mx = max(mx, cnt[s[j] - 'a']);
if ((j - i + 1) % unique == 0 && (j - i + 1) / unique == mx) {
result = max(result, j - i + 1);
}
}
}
return result;
}
};
// Time: O(n * (a + n)), a = len(set(s))
// Space: O(a)
// freq table
class Solution2 {
public:
int longestBalanced(string s) {
int result = 0;
for (int i = 0; i < size(s); ++i) {
unordered_map<char, int> cnt;
int mx = 0;
for (int j = i; j < size(s); ++j) {
mx = max(mx, ++cnt[s[j]]);
if ((j - i + 1) % size(cnt) == 0 && (j - i + 1) / size(cnt) == mx) {
result = max(result, j - i + 1);
}
}
}
return result;
}
};