首页 > 代码库 > Longest Palindromic Substring
Longest Palindromic Substring
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.
#include<iostream> #include<string.h> using namespace std; string longestPalindrome(string s) { int len = s.size(); int newlen = len * 2 + 1; char str[newlen]; int p[newlen]; int i, j, k, r, id; int maxr = 0; str[0] = '#'; for(i = 1, j = 0 ;s[j] != '\0'; i++, j++) { str[i] = s[j]; str[++i] = '#'; } str[i] = '\0'; p[0] = 1; for(i = 1, r = 1, id = 0; i < newlen; i++) { if(r > i) p[i] = (p[id * 2 - i] < (r - i))?p[id * 2 - i]:(r - i); else p[i] = 1; while(str[i + p[i]] != '\0' && str[i + p[i]] == str[i - p[i]]) p[i]++; if(p[i] >= maxr) { maxr = p[i]; id = i; r = i + p[i] - 1; } } string str1 = s.substr((id - maxr + 1) / 2, maxr - 1); return str1; } int main() { string str1 = longestPalindrome("c"); cout << str1 << endl; }
Longest Palindromic Substring
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。