647 Palindromic Substrings 迴文子串
Description:
Given a string s, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Example:
Example 1:
Input: s = "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: s = "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Constraints:
1 <= s.length <= 1000
s consists of lowercase English letters.
題目描述:
給定一個字符串,你的任務是計算這個字符串中有多少個迴文子串。
具有不同開始位置或結束位置的子串,即使是由相同的字符組成,也會被視作不同的子串。
示例 :
示例 1:
輸入:"abc"
輸出:3
解釋:三個迴文子串: "a", "b", "c"
示例 2:
輸入:"aaa"
輸出:6
解釋:6個迴文子串: "a", "a", "a", "aa", "aa", "aaa"
提示:
輸入的字符串長度不會超過 1000 。
思路:
中心擴展法
以 i 或者 [i, i + 1] 爲中心向兩端擴展直到不是迴文串
用一個全局變量記錄迴文串的數量
時間複雜度 O(n ^ 2), 空間複雜度 O(1)
用馬拉車算法可以將時間複雜度降至 O(n), 此時空間複雜度爲 O(n)
代碼:
C++:
class Solution
{
public:
int countSubstrings(string s)
{
int m = 0, r = 0, result = 0;
string t = "$#";
for (const char &c: s)
{
t += c;
t += '#';
}
int n = t.size();
t += '!';
vector<int> dp(n);
for (int i = 1; i < n; i++)
{
dp[i] = (i <= r) ? min(r - i + 1, dp[2 * m - i]) : 1;
while (t[i + dp[i]] == t[i - dp[i]]) ++dp[i];
if (i + dp[i] - 1 > r)
{
m = i;
r = i + dp[i] - 1;
}
result += (dp[i] >> 1);
}
return result;
}
};
Java:
class Solution {
private int result = 0;
public int countSubstrings(String s) {
for (int i = 0; i < s.length(); i++) {
count(s, i, i);
count(s, i, i + 1);
}
return result;
}
private void count(String s, int start, int end) {
while (start > -1 && end < s.length() && s.charAt(start--) == s.charAt(end++)) ++result;
}
}
Python:
class Solution:
def countSubstrings(self, s: str) -> int:
result, n = 0, len(s)
def count(start: int, end: int):
nonlocal result
while start > -1 and end < n and s[start] == s[end]:
start -= 1
end += 1
result += 1
for i in range(n):
count(i, i)
count(i, i + 1)
return result