Skip to content

Commit 77b5d75

Browse files
committed
feat: add solutions to lc problem: No.1156
No.1156.Swap For Longest Repeated Character Substring
1 parent be22de5 commit 77b5d75

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

solution/1100-1199/1156.Swap For Longest Repeated Character Substring/README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,36 @@ func min(a, b int) int {
192192
}
193193
```
194194

195+
### **TypeScript**
196+
197+
```ts
198+
function maxRepOpt1(text: string): number {
199+
const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0);
200+
const cnt: number[] = new Array(26).fill(0);
201+
for (const c of text) {
202+
cnt[idx(c)]++;
203+
}
204+
let ans = 0;
205+
let i = 0;
206+
const n = text.length;
207+
while (i < n) {
208+
let j = i;
209+
while (j < n && text[j] === text[i]) {
210+
++j;
211+
}
212+
const l = j - i;
213+
let k = j + 1;
214+
while (k < n && text[k] === text[i]) {
215+
++k;
216+
}
217+
const r = k - j - 1;
218+
ans = Math.max(ans, Math.min(cnt[idx(text[i])], l + r + 1));
219+
i = j;
220+
}
221+
return ans;
222+
}
223+
```
224+
195225
### **...**
196226

197227
```

solution/1100-1199/1156.Swap For Longest Repeated Character Substring/README_EN.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,36 @@ func min(a, b int) int {
168168
}
169169
```
170170

171+
### **TypeScript**
172+
173+
```ts
174+
function maxRepOpt1(text: string): number {
175+
const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0);
176+
const cnt: number[] = new Array(26).fill(0);
177+
for (const c of text) {
178+
cnt[idx(c)]++;
179+
}
180+
let ans = 0;
181+
let i = 0;
182+
const n = text.length;
183+
while (i < n) {
184+
let j = i;
185+
while (j < n && text[j] === text[i]) {
186+
++j;
187+
}
188+
const l = j - i;
189+
let k = j + 1;
190+
while (k < n && text[k] === text[i]) {
191+
++k;
192+
}
193+
const r = k - j - 1;
194+
ans = Math.max(ans, Math.min(cnt[idx(text[i])], l + r + 1));
195+
i = j;
196+
}
197+
return ans;
198+
}
199+
```
200+
171201
### **...**
172202

173203
```
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
function maxRepOpt1(text: string): number {
2+
const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0);
3+
const cnt: number[] = new Array(26).fill(0);
4+
for (const c of text) {
5+
cnt[idx(c)]++;
6+
}
7+
let ans = 0;
8+
let i = 0;
9+
const n = text.length;
10+
while (i < n) {
11+
let j = i;
12+
while (j < n && text[j] === text[i]) {
13+
++j;
14+
}
15+
const l = j - i;
16+
let k = j + 1;
17+
while (k < n && text[k] === text[i]) {
18+
++k;
19+
}
20+
const r = k - j - 1;
21+
ans = Math.max(ans, Math.min(cnt[idx(text[i])], l + r + 1));
22+
i = j;
23+
}
24+
return ans;
25+
}

0 commit comments

Comments
 (0)