Merge pull request #499 from jackeyjia/patch-18

add js solution for countSubstrings
This commit is contained in:
程序员Carl
2021-07-19 09:33:25 +08:00
committed by GitHub

View File

@ -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;
}
```
-----------------------