回文子串(中心拓展)
中心拓展
今天做到一道判断回文子串的问题,用到了这个方法。
以往做回文串只做过判断整一个字符串,就是用左右双指针遍历。但是如果用来解回文子串,就不太合适了。
需要用到中心拓展,遍历字符串,当前字符就是中心,往两边拓展。
还有Manacher,对中心拓展进行优化,不过就不太深入研究了。
代码
https://leetcode-cn.com/problems/palindromic-substrings/submissions/
class Solution {
public:
//中心拓展
int countSubstrings(string s) {
int ans=0;
for(int i = 0; i < s.size(); ++i){
for(int j = 0; j < 2; ++j){
int left = i;
int right = i + j;
while(left >= 0 && right <s.size()
&& s[left--] == s[right++]) ++ans;
}
}
return ans;
}
};
https://leetcode-cn.com/problems/longest-palindromic-substring/submissions/
class Solution {
public:
string longestPalindrome(string s) {
string ans;
for(int i = 0; i < s.size(); ++i){
for(int j = 0; j < 2; ++j){
int left = i, right = i+j;
while(left >= 0 && right < s.size()
&& s[left] == s[right]){
--left;
++right;
}
if(right - left - 1 > ans.size())
ans = s.substr(left + 1, right - left - 1);
}
}
return ans;
}
};