LeetCode(647):回文子串 Palindromic Substrings(Java)

234 篇文章 1 订阅
177 篇文章 0 订阅

2019.10.31 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

回文数和回文子串问题做过很多,总结一下:

  1. LeetCode(5):最长回文子串 Longest Palindromic Substring + Manacher算法(Java)

  2. LeetCode(9):回文数 Palindrome Number(Java)

  3. LeetCode125: 验证回文串

  4. LeetCode(131):分割回文串 Palindrome Partitioning(Java)

  5. LeetCode234: 回文链表

基本方法主要有回溯、动态规划、中心拓展三种。这三种当然也可以用于本题,其中回溯时间复杂度过高,可以考虑使用动态规划或者中心拓展。


传送门:回文子串

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。

具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。

示例 1:
输入: "abc"
输出: 3
解释: 三个回文子串: "a", "b", "c".

示例 2:
输入: "aaa"
输出: 6
说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".

注意:
输入的字符串长度不会超过1000。


/**
 *
 * Given a string, your task is to count how many palindromic substrings in this string.
 * The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
 * 给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
 * 具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。
 *
 */

public class PalindromicSubstrings {
    //动态规划
    public int countSubstrings(String s) {
        int[] dp = new int[s.length()];
        dp[0] = 1;
        for(int i = 1; i < s.length(); i++){
            dp[i] = dp[i - 1];
            for(int j = 0; j <= i; j++){
                dp[i] += isPalidromicSubstring(s, j, i) ? 1 : 0;
            }
        }
        return dp[s.length() - 1];
    }

    public boolean isPalidromicSubstring(String s, int beginIdx, int endIdx){
        while(beginIdx < endIdx){
            if(s.charAt(beginIdx++) != s.charAt(endIdx--)){
                return false;
            }
        }
        return true;
    }

    //中心拓展法
    public int countSubstrings2(String s) {
        int result = 0;
        for(int i = 0; i < s.length(); i++){
            int begin = i;
            int end = i;
            while(begin >= 0 && end < s.length() && s.charAt(begin) == s.charAt(end)){
                result++;
                begin--;
                end++;
            }
            begin = i - 1;
            end = i;
            while(begin >= 0 && end < s.length() && s.charAt(begin) == s.charAt(end)){
                result++;
                begin--;
                end++;
            }
        }
        return result;
    }

}




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值