#leetcode#647. Palindromic Substrings

https://leetcode.com/problems/palindromic-substrings/description/

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:

  1. The input string length won't exceed 1000.

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Palindrome无非两种做法, 1, two pointers,以每个character为中心或者以两个character之间的位置为中心向左右两边扩散, 找回文。 2, 用dp,套路理解完之后就是怎么套入不同的问题,比如这个,不让你找最长回文子串,而是找不同回文的个数,那么dp解法中只要当dp[i][j] == true 时, count++即可,two pointers做法就有点变化了。

之前看code ganker大神的two pointers做法,是这么找中心起点的:

for(int i = 0; i < 2 * s.length() - 1; i++){
    int left = i / 2;
    int right = i / 2;
    if(i % 2 == 1){
        right++;
    }
}

其实有点繁琐, 与其理解为找中心, 不如理解为如何初始化左指针与右指针,以character为中心, 则 left == right == index. 以两个character中间位置为中心, 则left == index, right == index + 1;

two pointers 解法:

class Solution {
    public int countSubstrings(String s) {
        if(s == null || s.length() == 0)
            return 0;
        int res = 0;
        for(int i = 0; i < s.length(); i++){
            res += count(s, i, i);
            res += count(s, i, i + 1);
        }
        return res;
    }
    
    private int count(String s, int l, int r){
        int res = 0;
        while(l >= 0 && r < s.length() && s.charAt(l--) == s.charAt(r++)){
            res++;
        }
        return res;
    }
}

dp解法:

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

这里two pointers解法是优于dp的, 因为dp需要O(n^2) space, two pointers只要O(1) space, 而时间复杂度都是O(n^2)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值