题目:
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".思路:
用一个数组记录当前能到该点的回文的开始下标,如果dp[i-1]里面每一个下标的前一个等于s[i],则把i-1放入dp[i]里面,还有一种情况是s[i-1]是否等于s[i],等于把i-1加入。算完dp[i]后累计计算能得到的回文。每次dp[i]至少会有一个本身可以加入。
class Solution {
public:
int countSubstrings(string s) {
vector<vector<int>> dp(s.size());
int re = 1;
dp[0].emplace_back(0);
for(int i = 1; i < s.size(); i++) {
for(int j = 0; j < dp[i - 1].size(); j++) {
if(dp[i-1][j]-1>=0&&s[dp[i-1][j]-1] == s[i]) dp[i].emplace_back(dp[i-1][j]-1);
if(dp[i-1][j] == i-1&&s[dp[i-1][j]] == s[i]) dp[i].emplace_back(dp[i-1][j]);
}
dp[i].emplace_back(i);
re+=dp[i].size();
}
return re;
}
};
还有就是马拉车算法,忘记怎么拉车的了,就没写
public class Solution {
public int countSubstrings(String s) {
String rs = "#";
//改造
for(int i = 0; i < s.length(); i++) rs = rs + s.charAt(i) + "#";
int[] RL = new int[rs.length()];//半径
int pos = 0, maxRight = 0, count = 0;
for(int i = 0; i < rs.length(); i++) {
if(i < maxRight) {
RL[i] = Math.min(maxRight - i, RL[2 * pos - i]);
}
while(i - RL[i] - 1 >= 0 && i + RL[i] + 1< rs.length() && rs.charAt(i - RL[i] - 1) == rs.charAt(i + RL[i] + 1)) {
RL[i]++;
}
if(i + RL[i] > maxRight) {
pos = i;
maxRight = i + RL[i];
}
count += (RL[i] + 1) / 2;
}
return count;
}
}
最优解居然是直接求解。。。
class Solution {
int cnt = 0;
void extend(string &s, int i, int j) {
while (i >= 0 && j <= s.size()) {
if (s[i--] != s[j++]) return;
cnt++;
}
}
public:
int countSubstrings(string s) {
for (int i = 0; i < s.size(); i++) {
extend(s, i, i + 1);
extend(s, i, i);
}
return cnt;
}
};