File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed
longest-repeating-character-replacement
longest-substring-without-repeating-characters Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n)
2+ // Space Complexity: O(1)
3+
4+ var characterReplacement = function ( s , k ) {
5+ let maxLen = 0 ;
6+ // initialize an array to store the count of each character.
7+ let charCounts = new Array ( 26 ) . fill ( 0 ) ;
8+ let start = 0 ;
9+
10+ // iterate the string with the end pointer.
11+ for ( let end = 0 ; end < s . length ; end ++ ) {
12+ // calculate the index of the character.
13+ let charIndex = s . charCodeAt ( end ) - 65 ;
14+ // update maxCount with the maximum count.
15+ maxLen = Math . max ( maxLen , ++ charCounts [ charIndex ] ) ;
16+
17+ // move the start pointer and decrement the count at that position.
18+ if ( end - start + 1 - maxLen > k ) {
19+ charCounts [ s . charCodeAt ( start ) - 65 ] -- ;
20+ start ++ ;
21+ }
22+ }
23+
24+ return s . length - start ;
25+ } ;
Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n)
2+ // Space Complexity: O(n)
3+
4+ var lengthOfLongestSubstring = function ( s ) {
5+ let charSet = new Set ( ) ;
6+
7+ let left = 0 ;
8+ let right = 0 ;
9+
10+ let maxLength = 0 ;
11+
12+ // iterate the string.
13+ while ( right < s . length ) {
14+ if ( ! charSet . has ( s [ right ] ) ) {
15+ // if the character isn't in the set, add it.
16+ charSet . add ( s [ right ] ) ;
17+ // move the right pointer to the right.
18+ right ++ ;
19+ // update the maximum length if the current window is larger.
20+ maxLength = Math . max ( maxLength , right - left ) ;
21+ } else {
22+ // if the character is in the set, remove the leftmost character.
23+ charSet . delete ( s [ left ] ) ;
24+ // move the left pointer to the right.
25+ left ++ ;
26+ }
27+ }
28+
29+ return maxLength ;
30+ } ;
You can’t perform that action at this time.
0 commit comments