Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 647. Palindromic Substrings #53

Open
Woodyiiiiiii opened this issue May 23, 2020 · 0 comments
Open

LeetCode 647. Palindromic Substrings #53

Woodyiiiiiii opened this issue May 23, 2020 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented May 23, 2020

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.

这道题跟**找出最长回文子字符串(5. Longest Palindromic Substring)**一样的思路。
首先直接用从中间字符遍历来判断,分为子字符串长度为奇数和偶数两种情况:

class Solution {
    private int subSum = 0;
    public int countSubstrings(String s) {
        int i = 0; 
        for (i = 0; i < s.length(); ++i) {
            countSub(s, i, i);
            countSub(s, i, i + 1);
        }
        return subSum;
    }
    public void countSub(String s, int left, int right) {
        while (left >= 0 && right < s.length()
              && s.charAt(left--) == s.charAt(right++))
            ++subSum;
    }
}

第二种就是DP的思路,声明一个dp二维数组,dp[i][j]表示子字符串i位置到j位置是否是回文,是为1,同时算入结果中,否为0。一开始要声明数组对角位置为1,表示单个字符串肯定是回文的。

一开始不知道如何使用DP,可以有这样一种思路:先考虑之间的DP关系,然后定义DP数组。比如这道题,如何判断[j...i]字符之间的substring是不是回文,就要判断[j+1...i-1]的字符串,如何可以定义二维DP数组。怎么感觉这才是正常思路

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

类似题目:

参考资料:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant