[LeetCode] 647. Palindromic Substrings 回文子字符串
Posted 轻风舞动
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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.
给了一个字符串,计算有多少个回文子字符串,不同index的都算作不同的子字符串。
解法1: DP
解法2: Manacher\'s Algorithm
Python: DP
class Solution(object): def countSubstrings(self, s): """ :type s: str :rtype: int """ n = len(s) count = 0 start, end, maxL = 0, 0, 0 dp = [[0] * n for _ in range(n)] for i in range(n): for j in range(i): dp[j][i] = (s[j] == s[i]) & ((i - j < 2) | dp[j + 1][i - 1]) if dp[j][i]: count += 1 dp[i][i] = 1 count += 1 return count
Python: Manacher\'s Algorithm
class Solution(object): def countSubstrings(self, s): """ :type s: str :rtype: int """ def manacher(s): s = \'^#\' + \'#\'.join(s) + \'#$\' P = [0] * len(s) C, R = 0, 0 for i in xrange(1, len(s) - 1): i_mirror = 2*C-i if R > i: P[i] = min(R-i, P[i_mirror]) while s[i+1+P[i]] == s[i-1-P[i]]: P[i] += 1 if i+P[i] > R: C, R = i, i+P[i] return P return sum((max_len+1)/2 for max_len in manacher(s))
C++:
class Solution { public: int countSubstrings(string s) { if (s.empty()) return 0; int n = s.size(), res = 0; for (int i = 0; i < n; ++i) { helper(s, i, i, res); helper(s, i, i + 1, res); } return res; } void helper(string s, int i, int j, int& res) { while (i >= 0 && j < s.size() && s[i] == s[j]) { --i; ++j; ++res; } } };
C++:
class Solution { public: int countSubstrings(string s) { int n = s.size(), res = 0; vector<vector<bool>> dp(n, vector<bool>(n, false)); for (int i = n - 1; i >= 0; --i) { for (int j = i; j < n; ++j) { dp[i][j] = (s[i] == s[j]) && (j - i <= 2 || dp[i + 1][j - 1]); if (dp[i][j]) ++res; } } return res; } };
类似题目:
[LeetCode] 5. Longest Palindromic Substring 最长回文子串
[LeetCode] 9. Palindrome Number 验证回文数字
[LeetCode] 125. Valid Palindrome 有效回文
[LeetCode] 516. Longest Palindromic Subsequence 最长回文子序列
All LeetCode Questions List 题目汇总
以上是关于[LeetCode] 647. Palindromic Substrings 回文子字符串的主要内容,如果未能解决你的问题,请参考以下文章
647. Palindromic Substrings(LeetCode)
Leetcode 647: Palindromic Substrings
LeetCode 647. Palindromic Substrings
[Leetcode]647.Palindromic Substrings