Movatterモバイル変換


[0]ホーム

URL:


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

Commit08e390c

Browse files
authored
add js solution for countSubstrings
1 parente70378f commit08e390c

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

‎problems/0647.回文子串.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,51 @@ func countSubstrings(s string) int {
361361
}
362362
```
363363

364+
Javascript
365+
> 动态规划
366+
```javascript
367+
const countSubstrings = (s) => {
368+
const strLen = s.length;
369+
let numOfPalindromicStr = 0;
370+
let dp = Array.from(Array(strLen), () => Array(strLen).fill(false));
371+
372+
for(let j = 0; j < strLen; j++) {
373+
for(let i = 0; i <= j; i++) {
374+
if(s[i] === s[j]) {
375+
if((j - i) < 2) {
376+
dp[i][j] = true;
377+
} else {
378+
dp[i][j] = dp[i+1][j-1];
379+
}
380+
numOfPalindromicStr += dp[i][j] ? 1 : 0;
381+
}
382+
}
383+
}
384+
385+
return numOfPalindromicStr;
386+
}
387+
```
364388

389+
> 双指针法:
390+
```javascript
391+
const countSubstrings = (s) => {
392+
const strLen = s.length;
393+
let numOfPalindromicStr = 0;
394+
395+
for(let i = 0; i < 2 * strLen - 1; i++) {
396+
let left = Math.floor(i/2);
397+
let right = left + i % 2;
398+
399+
while(left >= 0 && right < strLen && s[left] === s[right]){
400+
numOfPalindromicStr++;
401+
left--;
402+
right++;
403+
}
404+
}
405+
406+
return numOfPalindromicStr;
407+
}
408+
```
365409

366410

367411
-----------------------

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp