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;
    }
}
相关推荐
生态学者4 小时前
Global Change Biology | 森林越“步调一致”,反而越怕干旱?树木生长与叶片活动的同步之谜
大数据·人工智能·算法·r语言·微信公众平台
lsswear4 小时前
Agent 框架新手入门与实战部署指南
大数据·人工智能·算法
考研保研资料分享5 小时前
2022编辑出版跨保西北大学中国史:五校面试与九月补材料
面试·职场和发展
Data analyse4566 小时前
rnweb 回放数据量太大怎么办?分片存储与断点续传的实现思路
前端·网络·算法·数据分析
员工风险管理实务6 小时前
职务侵占有什么价值?岗位关联性与必要性判断
职场和发展
Navigator_Z7 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2088 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
光影少年8 小时前
AI Agent、自动化与未来工作
人工智能·算法·架构
牧羊人.3338 小时前
计算机视觉基础 第16章|EigenFace,FisherFace,LBPH传统人脸识别算法
人工智能·算法·计算机视觉
考研保研资料分享8 小时前
双非新闻学保研复盘:东华小组展示、长安面试与兰大预推免
面试·职场和发展