#leetcode#647. Palindromic Substrings

来源:互联网 发布:诺查丹玛斯 知乎 编辑:程序博客网 时间:2024/05/16 13:00

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: 3Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: "aaa"Output: 6Explanation: 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)

原创粉丝点击