Skip to content

Commit 9faa775

Browse files
authored
Create 1156-swap-for-longest-repeated-character-substring.js
1 parent 1202a3d commit 9faa775

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @param {string} text
3+
* @return {number}
4+
*/
5+
const maxRepOpt1 = function(text) {
6+
const count = [...text].reduce((a, c) => {
7+
a[c] = a[c] || 0;
8+
a[c]++;
9+
return a;
10+
}, {});
11+
let ans = 0;
12+
let i = 0;
13+
while (i < text.length) {
14+
let j = i;
15+
const c = text.charAt(i);
16+
while (j < text.length && text.charAt(j) === c) j++;
17+
if (j - i < count[c]) {
18+
let k = j + 1;
19+
while (k < text.length && text.charAt(k) === c && k - i < count[c]) k++;
20+
ans = Math.max(k - i, ans);
21+
} else ans = Math.max(j - i, ans);
22+
i = j;
23+
}
24+
return ans;
25+
};

0 commit comments

Comments
 (0)