leetcode 647. Palindromic Substrings(回文子串)

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.

Example 1:

Input: “abc”
Output: 3
Explanation: Three palindromic strings: “a”, “b”, “c”.

Example 2:

Input: “aaa”
Output: 6
Explanation: Six palindromic strings: “a”, “a”, “a”, “aa”, “aa”, “aaa”.

Note:
The input string length won’t exceed 1000.

找出字符串s中一共有多少个回文子串,相同的回文子串但是起止index不同也算不同的回文子串。

思路:
(1) DP
只需要记录i 到 j的子串是否是回文子串,遍历所有的子串,如果是回文子串就给结果+1
判断是否是回文子串:s[i] == s[j]时,如果i = j,指向的是同一字符,那显然是回文子串,如果i 和 j 是邻居,也是回文子串,如果i 和 j中间只隔一个字符,那么i 到 j也是回文子串。
但是,如果间隔的>2,就需要判断dp[i+1][j-1]
因为要看i + 1, j - 1,所以 i 要先计算右边的,j 要先计算左边的

注意判断的同时dp[i][j]自己也要更新

    public int countSubstrings(String s) {
        if(s == null || s.length() == 0) {
            return 0;
        }
        
        int n = s.length();
        int result = 0;
        boolean[][] dp = new boolean[n][n];
        
        for(int i = n-1; i >= 0; i--) {
            for(int j = i; j < n; j++) {
                dp[i][j] = s.charAt(i) == s.charAt(j) && (j-i <= 2 || dp[i+1][j-1]);
                if(dp[i][j]){
                    result ++;
                }
            }
        }
        
        return result;
    }

(2) 左右扩散
遍历每一个字符,以这个字符为中心左右扩散,每扩散一个对称的,就在结果+1。
当然分奇数和偶数的情况,奇数就是i 自己扩散,偶数情况就以i,i+1为中心扩散

class Solution {
    int result = 0;
    public int countSubstrings(String s) {
        if(s == null || s.length() == 0) {
            return 0;
        }
        
        int n = s.length();
    
        for(int i = 0; i < n; i++) {
            counter(s, i, i, n);
            counter(s, i, i+1, n);
        }
        
        return result;
    }
    
    void counter(String s, int left, int right, int n) {
        while(left >= 0 && right < n && s.charAt(left) == s.charAt(right)) {
            left --;
            right ++;
            result ++;
        }
    }
}

参考方法1方法2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值