647. Palindromic Substrings

Medium
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.

看的答案,解法比较巧妙,遍历String的各个位置的字符串,从第i个字符串开始向外expand, 或者是从第i个字符串和第i+1个字符串向外expand, 如果一直满足s.charAt(l) == s.charAt(j),就一直 count++计 palindrome的数 。

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

本题还有一种方法,跟Longest Palindrome Substring的做法很像,也是用dp

class Solution {
    public int countSubstrings(String s) {
        int res = 0;
        int n = s.length();
        boolean[][] dp = new boolean[n][n];
        for (int i = n - 1; i >= 0; i--){
            for (int j = i; j < n; j++){
                if (s.charAt(i) == s.charAt(j) && (( j - i < 3) || (dp[i + 1][j - 1]))){
                    dp[i][j] = true;
                    res++;
                }
            }
        }
        return res;
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/635b3642b7e6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞