Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb"
问题大意:在一个字符串中寻找最长的子字符串,该字符串是回数(即从左往右和从右往左读的结果是相同的)。
解题思路:遍历字符串,先找到回文最中间的部分aba或者bb,之后向两边搜索,更新长度和范围,找到长度最大的回文字符串。
#include<string> #include<set> #include<iostream> using namespace std; int start = 0, len = 1; void isPalindrome(const string &s, int a, int b) { while (a >= 0 && b < s.size() && s[a] == s[b]){ a--; b++; } if (len < b - a - 1) { start = a + 1; len = b - a - 1; } } string longestPalindrome(string s) { if (s.size() < 2) return s; //int start = 0, len = 1; for (int i = 1; i < s.size(); i++) { isPalindrome(s, i - 1, i + 1); isPalindrome(s, i - 1, i); } return s.substr(start, len); } int main(){ string s1 = "1234325234321"; string result = longestPalindrome(s1); cout << "最长回文串是: " << result << endl; cout << "最长回文串长度是: " << len << endl; getchar(); }