简介
题目链接:https://leetcode.cn/problems/palindromic-substrings/description/
解决方式:数组 + 暴力枚举 / 中心扩展法(双指针)
暴力枚举
思路:双重循环暴力枚举,枚举每一个可能的字符串,判断其是否是回文子串,是则计数加一否则处理下一个。
java
class Solution {
public int countSubstrings(String s) {
int n = s.length();
int count = 0;
// 枚举所有子串的起始位置
for (int i = 0; i < n; i++) {
// 枚举所有子串的结束位置
for (int j = i; j < n; j++) {
if (isPalindrome(s, i, j)) {
count++;
}
}
}
return count;
}
// 判断子串 s[i..j] 是否为回文串
private boolean isPalindrome(String s, int left, int right) {
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
中心扩展法
思路:回文子串会有中心点,可能是一个也可能是两个。我们可以迭代所有可能的中心点,判断当前中心点是否是回文子串,即向中心点周围扩展。
java
class Solution {
public int countSubstrings(String s) {
int n = s.length();
// 数量
int count = 0;
// 迭代
for(int center = 0; center < 2 * n - 1; center++){
// 考虑奇中心和偶中心,一共有 2n-1 个可能的中心点
// 初始化双指针,指向奇数中心点(一个数)或者偶数中心点(两个数)
int left = center / 2;
int right = left + center % 2;
// 向中心点周围拓展,看看是否是回文子串
while(left >= 0 && right < n && s.charAt(left) == s.charAt(right)){
// 计数加一
count++;
// 继续扩展
left--;
right++;
}
}
// 返回结果
return count;
}
}