Skip to content

Commit

Permalink
add js solution for countSubstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
jackeyjia authored Jul 17, 2021
1 parent e70378f commit 08e390c
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions problems/0647.回文子串.md
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,51 @@ func countSubstrings(s string) int {
}
```

Javascript
> 动态规划
```javascript
const countSubstrings = (s) => {
const strLen = s.length;
let numOfPalindromicStr = 0;
let dp = Array.from(Array(strLen), () => Array(strLen).fill(false));

for(let j = 0; j < strLen; j++) {
for(let i = 0; i <= j; i++) {
if(s[i] === s[j]) {
if((j - i) < 2) {
dp[i][j] = true;
} else {
dp[i][j] = dp[i+1][j-1];
}
numOfPalindromicStr += dp[i][j] ? 1 : 0;
}
}
}

return numOfPalindromicStr;
}
```

> 双指针法:
```javascript
const countSubstrings = (s) => {
const strLen = s.length;
let numOfPalindromicStr = 0;

for(let i = 0; i < 2 * strLen - 1; i++) {
let left = Math.floor(i/2);
let right = left + i % 2;

while(left >= 0 && right < strLen && s[left] === s[right]){
numOfPalindromicStr++;
left--;
right++;
}
}

return numOfPalindromicStr;
}
```


-----------------------
Expand Down

0 comments on commit 08e390c

Please sign in to comment.