File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
longest-repeating-character-replacement Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 알고달레 풀이 참고
3+ * @see https://www.algodale.com/problems/longest-repeating-character-replacement/
4+ *
5+ * TC: O(S)
6+ * right의 순회 + left의 순회
7+ * (곱이 아닌 더하기인 이유는 right 순회동안 left 순회의 최대 총합이 S이기 때문입니다.)
8+ *
9+ * SC: O(1)
10+ * 최악의 경우 26개의 소문자를 저장하는 memoryMap으로 인해 상수 복잡도를 갖게 됩니다.
11+ *
12+ * S: s.length
13+ */
14+
15+ /**
16+ * @param {string } s
17+ * @param {number } k
18+ * @return {number }
19+ */
20+ var characterReplacement = function ( s , k ) {
21+ // 1. 가장 긴 subString 길이
22+ let result = 0 ;
23+
24+ // 2. left, right 포인터 사이에서 등장한 문자 횟수를 기록한 Map과 최다 등장한 횟수를 기록한 변수
25+ const memory = new Map ( ) ;
26+ let maxCount = 0 ;
27+
28+ let left = 0 ;
29+ let right = 0 ;
30+
31+ while ( right < s . length ) {
32+ // 3. '새로운 문자(s[right])의 갯수 기록'과 '최다 등장한 횟수 갱신'
33+ const newCount = ( memory . has ( s [ right ] ) ? memory . get ( s [ right ] ) : 0 ) + 1 ;
34+ memory . set ( s [ right ] , newCount ) ;
35+ maxCount = Math . max ( maxCount , newCount ) ;
36+
37+ // 4. k만큼 변경가능한 subString 길이를 맞추기 위해 left 이동
38+ while ( right - left + 1 - maxCount > k ) {
39+ const newCount = memory . get ( s [ left ] ) - 1 ;
40+ memory . set ( s [ left ] , newCount ) ;
41+ left += 1 ;
42+ }
43+
44+ // 5. 가장 긴 subString 길이 갱신, right 이동
45+ result = Math . max ( result , right - left + 1 ) ;
46+ right += 1 ;
47+ }
48+
49+ return result ;
50+ } ;
You can’t perform that action at this time.
0 commit comments