Skip to content

Commit bf5c2af

Browse files
committed
Add solution #1156
1 parent 66e33c7 commit bf5c2af

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,156 LeetCode solutions in JavaScript
1+
# 1,157 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -904,6 +904,7 @@
904904
1147|[Longest Chunked Palindrome Decomposition](./solutions/1147-longest-chunked-palindrome-decomposition.js)|Hard|
905905
1154|[Day of the Year](./solutions/1154-day-of-the-year.js)|Easy|
906906
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|
907908
1161|[Maximum Level Sum of a Binary Tree](./solutions/1161-maximum-level-sum-of-a-binary-tree.js)|Medium|
908909
1189|[Maximum Number of Balloons](./solutions/1189-maximum-number-of-balloons.js)|Easy|
909910
1200|[Minimum Absolute Difference](./solutions/1200-minimum-absolute-difference.js)|Easy|
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
};

0 commit comments

Comments
 (0)