Skip to content

Commit d380482

Browse files
committed
feat : longest-repeating-character-replacement
1 parent ec95529 commit d380482

File tree

1 file changed

+119
-0
lines changed

1 file changed

+119
-0
lines changed
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
/**
2+
3+
input : String s
4+
output : after k times operation, return length of longest substring
5+
that consist of same letters
6+
7+
example
8+
AAAA << 4
9+
AAAB << AAA << 3
10+
11+
constraints:
12+
1) input string can be empty?
13+
nope. at least one letter
14+
2) string s contains whitespace? non-alphabetical chars?
15+
nope. only uppercase English letters
16+
3) range of k?
17+
[0, n], when n is the length of string s
18+
19+
ABAB
20+
AAAB
21+
AAAA
22+
23+
AABABBA
24+
AAAABBA
25+
AABBBBA
26+
27+
AABABBA
28+
l
29+
r
30+
count : 1
31+
4
32+
33+
solution 1: brute force
34+
ds : array
35+
algo : for loop
36+
37+
nested for loop
38+
iterate through the string s from index i = 0 to n
39+
set current character as 'target'
40+
set count = 0
41+
iterate through the string s from index j = i + 1 to n
42+
if next character is identical to 'target'
43+
continue;
44+
else
45+
increase count;
46+
47+
if count > k
48+
break and save length
49+
50+
if count <=k compare length with max
51+
ABAB
52+
i
53+
j
54+
target = A
55+
count = 1
56+
ABAB << count = 2, length = 4
57+
tc : O(n^2)
58+
sc : O(1)
59+
60+
solution 2: two pointer
61+
62+
AABCABBA
63+
l
64+
r
65+
A : 1
66+
B : 1
67+
C : 1
68+
count = 1
69+
res = 4
70+
set two pointer l and r
71+
set count to 0;
72+
set maxFrequency character s[0];
73+
74+
move r pointer to right
75+
if current char is not maxFreqChar
76+
count + 1;
77+
else
78+
continue;
79+
80+
if count > k
81+
while count <= k
82+
move leftpointer right;
83+
update frequency
84+
set max Frequency character at each iteration O(26)
85+
update count
86+
87+
tc: O(n)
88+
sc : O(26) ~= O(1)
89+
*/
90+
91+
class Solution {
92+
public int characterReplacement(String s, int k) {
93+
int l = 0, r = 1, maxFreq = 1, res = 1;
94+
int n = s.length();
95+
int[] freq = new int[26];
96+
// base case;
97+
char maxFreqChar = s.charAt(0);
98+
freq[maxFreqChar - 'A']++;
99+
// loop
100+
while (r < n) {
101+
char next = s.charAt(r);
102+
maxFreq = Math.max(maxFreq, ++freq[next - 'A']);
103+
104+
while(r - l + 1 - maxFreq > k) {
105+
freq[s.charAt(l) - 'A']--;
106+
l++;
107+
for(int i = 0; i <26; i++) {
108+
if(freq[i] > maxFreq) {
109+
maxFreq = freq[i];
110+
}
111+
}
112+
}
113+
res = Math.max(res, r - l+1);
114+
r++;
115+
}
116+
117+
return res;
118+
}
119+
}

0 commit comments

Comments
 (0)