Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
- The input string length won't exceed 1000.
/**
* @param {string} s
* @return {number}
*/
var countSubstrings = function(s) {
var count=s.length;
const len =s.length;
//以i为中心扩展
for(var i = 1 ; i <len-1;i++){
var num=1;
while((i-num)>=0&&(i+num)<len){
if(s[i-num]===s[i+num]){
count++;
num++;
}else{
break;
}
}
}
//以i,i+1的中心为中心扩展
for(var i = 0 ; i <len;i++){
var num=1;
while((i+1-num)>=0&&(i+num)<len){
if(s[i+1-num]===s[i+num]){
count++;
num++;
}else{
break;
}
}
}
return count;
};
看了下别人的代码。思路跟我一样,代码简洁多了
class Solution {
public:
int countSubstrings(string s) {
int res = 0, n = s.length();
for(int i = 0; i<n ;i++ ){
// i or (i-1, i) is the middle index of the substring, 2*j + 1 or 2*j + 2 is the length of the substring
for(int j = 0; i-j >=0 && i+j <n && s[i-j] == s[i+j]; j++)res++;
for(int j = 0; i-1-j >=0 && i+j <n && s[i-1-j] == s[i+j];j++)res++;
}
return res;
}
};