标签:
Description:
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
Code:
string longestPalindrome(string s) { if (s=="") return s; unsigned int n = s.size(); int max_start = 0, max_end = 0; bool table[1000][1000]; for (int i = 0; i < n-1; ++i) { table[i][i] = true; table[i][i+1] = (s[i]==s[i+1])?true:false; if (table[i][i+1]) { max_start = i; max_end = i+1; } } table[n-1][n-1] = true; for (int len = 3; len <= n; ++len) { for (int i = 0; i < n-len+1; ++i) { int j = i+len-1; if (s[i]==s[j]) { table[i][j] = table[i+1][j-1]; if (table[i][j]) { if (j-i+1 > max_end-max_start+1) { max_start = i; max_end = j; } } } else table[i][j] = false; } } return s.substr(max_start, max_end-max_start+1); }
标签:
原文地址:http://www.cnblogs.com/happygirl-zjj/p/4778761.html