题目
给定一个字符串 s ,请计算这个字符串中有多少个回文子字符串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
示例 1:
输入:s = “abc”
输出:3
解释:三个回文子串: “a”, “b”, “c”
示例 2:
输入:s = “aaa”
输出:6
解释:6个回文子串: “a”, “a”, “a”, “aa”, “aa”, “aaa”
提示:
1 <= s.length <= 1000
s 由小写英文字母组成
代码和思路
class Solution {
// 定位对称中心,由内向外扩大范围
// 回文字符串又分奇数偶数,那么中心对称就分为2个起步和一个起步
public int countSubstrings(String s) {
// 边界判断
if(s.length() == 0 || s == null){
return 0;
}
int count = 0;
for(int i = 0;i < s.length();i++){
// 一个对称中心,找到所有的奇数
count += getCount(s,i,i);
// 定义两个对称中心,找到所有偶数
count += getCount(s,i,i+1);
}
return count;
}
private int getCount(String s,int start,int end){
int count = 0;
// 从内往外,所以判断条件要注意
while(start >= 0 && end <= s.length()-1){
if(s.charAt(start) == s.charAt(end)){
count++;
}
// 只要又一个不一样,那么后面也不可能是回文串了,直接break就行了
if(s.charAt(start) != s.charAt(end)){
break;
}
start--;
end++;
}
return count;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/96181.html