剑指 Offer II 020. 回文子字符串的个数https://leetcode.cn/problems/a7VOhD/
难度中等52
给定一个字符串 s
,请计算这个字符串中有多少个回文子字符串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
示例 1:
输入:s = "abc" 输出:3 解释:三个回文子串: "a", "b", "c"
示例 2:
输入:s = "aaa" 输出:6 解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
提示:
1 <= s.length <= 1000
s
由小写英文字母组成
注意:本题与主站 647 题相同:力扣
class Solution {
public int countSubstrings(String s) {
int n = s.length(); //存储n的长度
int ans = 0; //存储结果
for(int i=0;i<2*n-1;i++) //长度为n的字符串有2*n-1个回文中心
{
int l=i/2; //回文中心左起始位置
int r=i/2+i%2; //回文中心右起始位置
while(l>=0 && r<n && s.charAt(l)==s.charAt(r))
{
--l;
++r;
++ans;
}
}
return ans;
}
}
class Solution {
public int countSubstrings(String s) {
int len = s.length();
int ans = 0;
for(int i=0;i<=len;i++)
{
for(int j=i+1;j<=len;j++)
{
String str = s.substring(i,j);
int start = 0,end=str.length()-1;
while(start<end)
{
if(str.charAt(start)!=str.charAt(end)) break;
start++;
end--;
}
if(start>=end) ans++;
}
}
return ans;
}
}