File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
longest-repeating-character-replacement Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Collections ;
2
+ import java .util .HashMap ;
3
+ import java .util .Map ;
4
+
5
+ class Solution {
6
+ public int characterReplacement (String s , int k ) {
7
+ // ํ์ด: ์ฌ๋ผ์ด๋ฉ ์๋์ฐ๋ฅผ ํ์ฉํด ๋ถ๋ถ ๋ฌธ์์ด์ ๊ตฌํ๋ค
8
+ // ์ข
๋ฃ ์ธ๋ฑ์ค๋ฅผ ์ฆ๊ฐ์ํค๊ณ , ๋ถ๋ถ ๋ฌธ์์ด ๊ธธ์ด์์ ๊ฐ์ฅ ๋ง์ด ๋ค์ด์๋ ๋ฌธ์์ ์๋ฅผ ๋บ ๊ฐ์ด k๋ณด๋ค ํฐ์ง ๋น๊ตํ๋ค.
9
+ // ํฌ๋ค๋ฉด, ์์ ์ธ๋ฑ์ค๋ฅผ ์ฆ๊ฐ์ํจ๋ค.
10
+ // ๋๊น์ง ๋ฐ๋ณตํ๋ฉด์ ์ต๋ ๊ธธ์ด๋ฅผ ์ ์ฅํ๋ค๊ฐ ๋ฐํํ๋ค.
11
+ // TC: O(N)
12
+ // SC: O(N)
13
+ var maxLength = 0 ;
14
+ var start = 0 ;
15
+ var end = 0 ;
16
+ Map <Character , Integer > countByChar = new HashMap <>();
17
+
18
+ while (end < s .length ()) {
19
+ countByChar .put (s .charAt (end ), countByChar .getOrDefault (s .charAt (end ), 0 ) + 1 );
20
+
21
+ while ((end - start + 1 - Collections .max (countByChar .values ())) > k ) {
22
+ countByChar .put (s .charAt (start ), countByChar .get (s .charAt (start )) - 1 );
23
+ start += 1 ;
24
+ }
25
+ maxLength = Math .max (end - start + 1 , maxLength );
26
+ end ++;
27
+ }
28
+
29
+ return maxLength ;
30
+ }
31
+ }
You canโt perform that action at this time.
0 commit comments