File tree Expand file tree Collapse file tree 2 files changed +46
-1
lines changed Expand file tree Collapse file tree 2 files changed +46
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,156 LeetCode solutions in JavaScript
1
+ # 1,157 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
904
904
1147|[ Longest Chunked Palindrome Decomposition] ( ./solutions/1147-longest-chunked-palindrome-decomposition.js ) |Hard|
905
905
1154|[ Day of the Year] ( ./solutions/1154-day-of-the-year.js ) |Easy|
906
906
1155|[ Number of Dice Rolls With Target Sum] ( ./solutions/1155-number-of-dice-rolls-with-target-sum.js ) |Medium|
907
+ 1156|[ Swap For Longest Repeated Character Substring] ( ./solutions/1156-swap-for-longest-repeated-character-substring.js ) |Medium|
907
908
1161|[ Maximum Level Sum of a Binary Tree] ( ./solutions/1161-maximum-level-sum-of-a-binary-tree.js ) |Medium|
908
909
1189|[ Maximum Number of Balloons] ( ./solutions/1189-maximum-number-of-balloons.js ) |Easy|
909
910
1200|[ Minimum Absolute Difference] ( ./solutions/1200-minimum-absolute-difference.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 1156. Swap For Longest Repeated Character Substring
3
+ * https://leetcode.com/problems/swap-for-longest-repeated-character-substring/
4
+ * Difficulty: Medium
5
+ *
6
+ * You are given a string text. You can swap two of the characters in the text.
7
+ *
8
+ * Return the length of the longest substring with repeated characters.
9
+ */
10
+
11
+ /**
12
+ * @param {string } text
13
+ * @return {number }
14
+ */
15
+ var maxRepOpt1 = function ( text ) {
16
+ const map = new Map ( ) ;
17
+ for ( const char of text ) {
18
+ map . set ( char , ( map . get ( char ) || 0 ) + 1 ) ;
19
+ }
20
+
21
+ let result = 0 ;
22
+ for ( let i = 0 ; i < text . length ; ) {
23
+ const currentChar = text [ i ] ;
24
+ const segmentStart = i ;
25
+
26
+ while ( i < text . length && text [ i ] === currentChar ) i ++ ;
27
+ const segmentLength = i - segmentStart ;
28
+
29
+ const totalAvailable = map . get ( currentChar ) ;
30
+ if ( i < text . length && segmentLength < totalAvailable ) {
31
+ const nextStart = i + 1 ;
32
+ let nextLength = 0 ;
33
+ while ( nextStart + nextLength < text . length && text [ nextStart + nextLength ] === currentChar ) {
34
+ nextLength ++ ;
35
+ }
36
+ result = Math . max ( result , Math . min ( segmentLength + nextLength + 1 , totalAvailable ) ) ;
37
+ }
38
+ result = Math . max ( result , Math . min (
39
+ segmentLength + ( totalAvailable > segmentLength ? 1 : 0 ) , totalAvailable
40
+ ) ) ;
41
+ }
42
+
43
+ return result ;
44
+ } ;
You can’t perform that action at this time.
0 commit comments