Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fe3aa4f

Browse files
Merge pull request youngyangyang04#1378 from xiaofei-2020/dp52
添加(0647.回文子串.md):增加typescript版本
2 parents bf38ac9 + f650146 commit fe3aa4f

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

‎problems/0647.回文子串.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,63 @@ const countSubstrings = (s) => {
406406
}
407407
```
408408

409+
TypeScript:
410+
411+
> 动态规划:
412+
413+
```typescript
414+
function countSubstrings(s: string): number {
415+
/**
416+
dp[i][j]: [i,j]区间内的字符串是否为回文(左闭右闭)
417+
*/
418+
const length: number = s.length;
419+
const dp: boolean[][] = new Array(length).fill(0)
420+
.map(_ => new Array(length).fill(false));
421+
let resCount: number = 0;
422+
// 自下而上,自左向右遍历
423+
for (let i = length - 1; i >= 0; i--) {
424+
for (let j = i; j < length; j++) {
425+
if (
426+
s[i] === s[j] &&
427+
(j - i <= 1 || dp[i + 1][j - 1] === true)
428+
) {
429+
dp[i][j] = true;
430+
resCount++;
431+
}
432+
}
433+
}
434+
return resCount;
435+
};
436+
```
437+
438+
> 双指针法:
439+
440+
```typescript
441+
function countSubstrings(s: string): number {
442+
const length: number = s.length;
443+
let resCount: number = 0;
444+
for (let i = 0; i < length; i++) {
445+
resCount += expandRange(s, i, i);
446+
resCount += expandRange(s, i, i + 1);
447+
}
448+
return resCount;
449+
};
450+
function expandRange(s: string, left: number, right: number): number {
451+
let palindromeNum: number = 0;
452+
while (
453+
left >= 0 && right < s.length &&
454+
s[left] === s[right]
455+
) {
456+
palindromeNum++;
457+
left--;
458+
right++;
459+
}
460+
return palindromeNum;
461+
}
462+
```
463+
464+
465+
409466

410467
-----------------------
411468
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /