Run ID:115521
提交时间:2025-03-31 15:22:08
//这道题目要求判断一个字符串中是否包含长度大于等于2的回文子串。与判断整个字符串是否为回文不同,这里需要检查字符串中的任意子串是否为回文。 //可以通过动态规划或者中心扩展法来解决这个问题。这里提供一个简单且高效的中心扩展法的实现。 //中心扩展法思路 //中心点的选择:回文子串可能以一个字符为中心(奇数长度回文),也可能以两个字符为中心(偶数长度回文)。因此,需要遍历每个可能的中心点。 //扩展检查:从中心点向两边扩展,检查是否满足回文的条件(即左右两侧的字符是否相等)。 //输出结果:如果找到任意一个长度大于等于2的回文子串,则输出 Yes,否则输出 No #include <iostream> #include <string> using namespace std; // 函数:判断以某个中心点扩展的回文子串 bool isPalindromeSubstring(const string& s, int left, int right) { while (left >= 0 && right < s.length() && s[left] == s[right]) { left--; right++; } return right - left - 1 >= 2; // 如果回文子串长度大于等于2,返回true } int main() { string s; cin >> s; // 输入字符串 int n = s.length(); // 获取字符串长度 bool hasPalindrome = false; // 标记是否找到回文子串 // 遍历每个可能的中心点 for (int i = 0; i < n; ++i) { // 检查奇数长度的回文子串(以单个字符为中心) if (isPalindromeSubstring(s, i, i)) { hasPalindrome = true; break; } // 检查偶数长度的回文子串(以两个字符为中心) if (isPalindromeSubstring(s, i, i + 1)) { hasPalindrome = true; break; } } // 输出结果 if (hasPalindrome) { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0; }