编写一个C++代码对给定的字符串本题要求你输出最长对称子串的长度。例如给定Is PAT&TAP symmetric最长对称子串为s PAT&TAP s于是你应该输出11。输入格式:输入在一行中给出长度不超过1000的非空字符串。输出格式:在一行中输出最长对称子串的长度。输入样例:Is PAT&TAP symmetric输出样例:11
#include
bool isPalindrome(string str) { int len = str.length(); for (int i = 0; i < len / 2; i++) { if (str[i] != str[len - i - 1]) { return false; } } return true; }
int longestPalindrome(string str) { int len = str.length(); int maxLength = 0; for (int i = 0; i < len; i++) { for (int j = i + 1; j <= len; j++) { string substr = str.substr(i, j - i); if (isPalindrome(substr) && substr.length() > maxLength) { maxLength = substr.length(); } } } return maxLength; }
int main() { string str; getline(cin, str); int length = longestPalindrome(str); cout << length << endl; return 0;
原文地址: http://www.cveoy.top/t/topic/hAbT 著作权归作者所有。请勿转载和采集!