Input: s ="bcbbbcba"Output: 4Explanation:
The following substring has a length of 4 and contains at most two occurrences
of each character:`"bcbb _bcba_ "`.
We want the longest substring where each character appears at most twice. We can use a sliding window and a hash map to count occurrences. When a character appears more than twice, move the left pointer to shrink the window until all counts are at most two.
classSolution {
public:int maxLengthSubstring(string s) {
unordered_map<char, int> cnt;
int l =0, ans =0;
for (int r =0; r < s.size(); ++r) {
cnt[s[r]]++;
while (cnt[s[r]] >2) {
cnt[s[l]]--;
l++;
}
ans = max(ans, r - l +1);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funcmaxLengthSubstring(sstring) int {
cnt:=map[byte]int{}
l, ans:=0, 0forr:=0; r < len(s); r++ {
cnt[s[r]]++forcnt[s[r]] > 2 {
cnt[s[l]]--l++ }
ifr-l+1 > ans {
ans = r-l+1 }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicintmaxLengthSubstring(String s) {
Map<Character, Integer> cnt =new HashMap<>();
int l = 0, ans = 0;
for (int r = 0; r < s.length(); ++r) {
cnt.put(s.charAt(r), cnt.getOrDefault(s.charAt(r), 0) + 1);
while (cnt.get(s.charAt(r)) > 2) {
cnt.put(s.charAt(l), cnt.get(s.charAt(l)) - 1);
l++;
}
ans = Math.max(ans, r - l + 1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funmaxLengthSubstring(s: String): Int {
val cnt = mutableMapOf<Char, Int>()
var l = 0var ans = 0for (r in s.indices) {
cnt[s[r]] = cnt.getOrDefault(s[r], 0) + 1while (cnt[s[r]]!! > 2) {
cnt[s[l]] = cnt[s[l]]!! - 1 l++ }
ans = maxOf(ans, r - l + 1)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defmaxLengthSubstring(self, s: str) -> int:
from collections import defaultdict
cnt: dict[str, int] = defaultdict(int)
l = ans =0for r, c in enumerate(s):
cnt[c] +=1while cnt[c] >2:
cnt[s[l]] -=1 l +=1 ans = max(ans, r - l +1)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnmax_length_substring(s: String) -> i32 {
use std::collections::HashMap;
let s = s.as_bytes();
letmut cnt = HashMap::new();
let (mut l, mut ans) = (0, 0);
for r in0..s.len() {
*cnt.entry(s[r]).or_insert(0) +=1;
while*cnt.get(&s[r]).unwrap() >2 {
*cnt.get_mut(&s[l]).unwrap() -=1;
l +=1;
}
ans = ans.max((r - l +1) asi32);
}
ans
}
}