中心扩散法
int expand(string s, int i, int j)
{
int n = s.size();
int cnt = 0;
while(i >= 0 && j < n)
{
if(s[i] == s[j])
{
cnt++;
i--;
j++;
}
else break;
}
return cnt;
}
最长回文子串
题目链接:https://leetcode-cn.com/problems/longest-palindromic-substring/
class Solution {
public:
pair<int, int> expand(string s, int i, int j)
{
while(i >= 0 && j < s.size() && s[i] == s[j])
{
--i;
++j;
}
return {i + 1, j - 1};
}
string longestPalindrome(string s) {
int cnt = 0;
pair<int, int> pii;
for(int i = 0; i < s.size(); i++)
{
auto val_1 = expand(s, i, i);
auto val_2 = expand(s, i, i + 1);
int cnt_1 = val_1.second - val_1.first + 1;
if(cnt_1 > cnt)
{
cnt = cnt_1;
pii = val_1;
}
int cnt_2 = val_2.second - val_2.first + 1;
if(cnt_2 > cnt)
{
cnt = cnt_2;
pii = val_2;
}
}
return s.substr(pii.first, pii.second - pii.first + 1);
}
};
回文子串
题目链接:https://leetcode-cn.com/problems/palindromic-substrings/
class Solution {
public:
int expand(string s, int i, int j)
{
int n = s.size();
int cnt = 0;
while(i >= 0 && j < n)
{
if(s[i] == s[j])
{
cnt++;
i--;
j++;
}
else break;
}
return cnt;
}
int countSubstrings(string s) {
int cnt = 0;
for(int i = 0; i < s.size(); i++)
{
cnt += expand(s, i, i);
cnt += expand(s, i, i + 1);
}
return cnt;
}
};