34
34
*/
35
35
public class _424 {
36
36
37
- //credit: https://discuss.leetcode.com/topic/63494/java-12-lines-o-n-sliding-window-solution-with-explanation
38
- public int characterReplacement (String s , int k ) {
39
- int len = s .length ();
40
- int [] count = new int [26 ];
41
- int start = 0 ;
42
- int maxCount = 0 ;
43
- int maxLength = 0 ;
44
- for (int end = 0 ; end < len ; end ++) {
45
- maxCount = Math .max (maxCount , ++count [s .charAt (end ) - 'A' ]);
46
- while (end - start + 1 - maxCount > k ) {
47
- count [s .charAt (start ) - 'A' ]--;
48
- start ++;
49
- }
50
- maxLength = Math .max (maxLength , end - start + 1 );
51
- }
52
- return maxLength ;
53
- }
54
-
55
- //this one can pass all test from test1 to test5, but tests like test6 won't pass
56
- public int characterReplacement_failed_attempt (String s , int k ) {
57
- int longest = 0 ;
58
- if (s == null || s .length () == 0 ) {
59
- return 0 ;
60
- }
61
- for (int i = 0 ; i < s .length (); i ++) {
62
- int count = 1 ;
63
- char val = s .charAt (i );
64
- for (int j = i + 1 ; j < s .length (); j ++) {
65
- if (s .charAt (j ) == val ) {
66
- count ++;
67
- } else {
68
- if (k > 0 ) {
69
- count ++;
70
- char replace = s .charAt (j );
71
- int kCounter = k - 1 ;
72
- for (int p = j + 1 ; p < s .length (); p ++) {
73
- if (kCounter <= 0 ) {
74
- if (val == s .charAt (p )) {
75
- count ++;
76
- } else {
77
- longest = Math .max (longest , count );
78
- break ;
79
- }
80
- } else {
81
- if (val == s .charAt (p )) {
82
- count ++;
83
- } else if (replace == s .charAt (p )) {
84
- count ++;
85
- kCounter --;
86
- } else {
87
- longest = Math .max (longest , count );
88
- break ;
89
- }
90
- }
91
- }
92
- if (kCounter <= 0 ) {
93
- longest = Math .max (longest , count );
94
- break ;
95
- }
96
- } else {
97
- if (s .charAt (j ) == val ) {
98
- count ++;
99
- } else {
100
- longest = Math .max (longest , count );
101
- break ;
102
- }
103
- }
37
+ public static class Solution1 {
38
+ //credit: https://discuss.leetcode.com/topic/63494/java-12-lines-o-n-sliding-window-solution-with-explanation
39
+ public int characterReplacement (String s , int k ) {
40
+ int len = s .length ();
41
+ int [] count = new int [26 ];
42
+ int start = 0 ;
43
+ int maxCount = 0 ;
44
+ int maxLength = 0 ;
45
+ for (int end = 0 ; end < len ; end ++) {
46
+ maxCount = Math .max (maxCount , ++count [s .charAt (end ) - 'A' ]);
47
+ while (end - start + 1 - maxCount > k ) {
48
+ count [s .charAt (start ) - 'A' ]--;
49
+ start ++;
104
50
}
105
- longest = Math .max (longest , count );
51
+ maxLength = Math .max (maxLength , end - start + 1 );
106
52
}
107
- longest = Math . max ( longest , count ) ;
53
+ return maxLength ;
108
54
}
109
- return longest ;
110
55
}
111
-
112
- }
56
+ }
0 commit comments