Topic links:
Title Description
1 violence
Complexity Analysis
time complexity: O (n ^ 3)
space complexity: O (1)
class Solution {
public:
int countSubstrings(string s) {
if(s.empty()) return 0;
int ret = 0;
for(int i = 0; i<s.size(); ++i){
for(int j = i; j<s.size(); ++j){
if (isPalindrome(s,i,j))
++ ret;
}
}
return ret;
}
// 判断一个字符串是否为回文串
bool isPalindrome(string s, int i, int j){
while(i<=j){
if(s[i++]!=s[j--])
return false;
}
return true;
}
};
2 from the central character extension
A central palindrome string character position is fixed, may be the center position + palindromic sequence length uniquely represent a palindromic sequence
A bit string to the center, extend to both sides;
respectively count the number of odd and even length of palindromic sequence
Complexity Analysis
time complexity: O (n)
complexity of space: O (1)
class Solution {
public:
int countSubstrings(string s) {
if(s.empty()) return 0;
int ret = 0;
for(int i = 0; i<s.size(); ++i){
count(s,i,i,ret); // 以i位置字符为中心,长度为奇数的回文串数目
count(s,i,i+1,ret); // 以i,i+1位置字符为中心,长度为偶数的回文串数目
}
return ret;
}
void count(string &s, int begin, int end, int &ret){
while (begin>=0 && end<s.size() && s[begin--] == s[end++])
++ ret;
}
};
3 Dynamic Programming
Two-dimensional array of dp[i][j]
string representing s(i,j)
whether the string is a palindrome.
(1) First, a string of length 1, 2 need to initialize its value dp
(2) for a length of 3 ~ len
dp[i][j] = (s[i] == s[j] && dp[i+1][j-1])
Note that the above formula when traversing from front to back is not traversed, dp [i] [j] depends on the dp [i + 1] [j -1]. Therefore, the coordinate processing needs to be done, so that the entire process is traversed from front to back.
Because the previously calculated value dp string length 1, so we from i = 3~len
traversing the length of the substring starts, and checks j = 0~len-i+1
as a starting point end = j + i -1
for the end of the sub-string is palindromic substring.
dp[j][end] = (s[j] == s[end] && dp[j+1][end-1])
Complexity Analysis
time complexity: O (n ^ 2)
Complexity Space: O (n ^ 2)
/*
* 动态规划
* 时间复杂度O(n^2) 空间复杂度O(n^2)
*/
class Solution {
public:
int countSubstrings(string s) {
if(s.empty()) return 0;
int len = s.size();
vector<vector<bool >> dp(len, vector<bool > (len, false));
int ret = 0;
// 首先处理长度为1和2的子串
for (int i = 0; i < len; ++i) {
dp[i][i] = true; // 初始化长度为1的回文串
++ ret;
}
for (int i = 0; i< len -1; ++i){
if (s[i] == s[i+1]){
dp[i][i+1] = true; // 初始化长度为2的回文串
++ ret;
}
}
// i为遍历的子串长度,j为起始节点
for (int i = 3; i <= len ; ++i) {
for (int j = 0; j <= len -i + 1; ++j) {
int end = j+i-1;
if(s[j] == s[end] && dp[j+1][end-1]){
dp[j][end] = true;
++ ret;
}
}
}
return ret;
}
};