LeetCode:647. 回文子串

简介

题目链接: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;
    }
}
相关推荐
imaol127 分钟前
文件编程--标准IO
linux·运维·算法
青 春 记 忆31 分钟前
LeetCode 121. 买卖股票的最佳时机|Python 解法详解
python·算法·leetcode
stolentime43 分钟前
AT_agc066_a [AGC066A] Adjacent Difference题解
c++·算法·贪心算法·构造
渣波1 小时前
深度解析:LeetCode 51. N 皇后 —— 回溯算法的巅峰之作
算法
咪饭只吃一小碗1 小时前
# C++ STL 常用容器方法全面总结vector / map / set / unordered_map / unordered_set
算法
daad7771 小时前
802.11 前导码与 STF 深度解析(含检测算法与 5G 对比
人工智能·算法·5g·wifi·802.11·前导码
Navigator_Z2 小时前
LeetCode //C - 1203. Sort Items by Groups Respecting Dependencies
c语言·算法·leetcode
LayZhangStrive3 小时前
提示词沉淀 - 使用豆包时平时提问题
面试·职场和发展·prompt·提示词·豆包
我变成萤火虫3 小时前
2026 ICPC沈阳邀请赛Vp补题
数据结构·c++·算法·贪心算法·stl·排序算法·动态规划