File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
December 2024 Leetcode Solution Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ impl Solution {
2
+ pub fn maximum_length ( s : String ) -> i32 {
3
+ fn is_valid ( s : & str , n : usize , x : usize ) -> bool {
4
+ let mut freq = vec ! [ 0 ; 26 ] ;
5
+ let bytes = s. as_bytes ( ) ;
6
+ let mut i = 0 ;
7
+ while i < n {
8
+ let mut j = i + 1 ;
9
+ while j < n && bytes[ j] == bytes[ i] {
10
+ j += 1 ;
11
+ }
12
+ let index = ( bytes[ i] - b'a' ) as usize ;
13
+ freq[ index] += ( j - i) . saturating_sub ( x - 1 ) ;
14
+ if freq[ index] >= 3 {
15
+ return true ;
16
+ }
17
+ i = j;
18
+ }
19
+ false
20
+ }
21
+
22
+ let n = s. len ( ) ;
23
+ let mut l = 0 ;
24
+ let mut r = n;
25
+ while l < r {
26
+ let mid = ( l + r + 1 ) / 2 ;
27
+ if is_valid ( & s, n, mid) {
28
+ l = mid;
29
+ } else {
30
+ r = mid - 1 ;
31
+ }
32
+ }
33
+ if l == 0 { -1 } else { l as i32 }
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments