#include <iostream> #include <string> #include <vector> using namespace std; /* 一个字符串中最长的回文子串 思路:以某一个字符为中心开始向两边遍历 这样查找最长的子串 */ int LongestPalindromicSub(string& str) { int pre,next,i; int maxlen=0; int pos; for(i=0;i<str.length();i++) { pre =i-1; next = i+1; while(pre>=0 && next<str.length()) { if(str[pre] == str[next]) { pre--; next++; } else break; } if(maxlen < (i-pre)*2+1) { maxlen = next-pre-1; pos = pre+1; } } // cout<<pos<<endl; return maxlen; } int main() { string str("ADOEBEOODEBEDCAAACDABDDBDAD"); cout<<LongestPalindromicSub(str)<<endl; return 0; }
Longest Palindromic Substring--LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44802073