标签:
leetcode - 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.
class Solution { public: string longestPalindrome(string s) { string res; int posSubStrBegin=0, posSubStrEnd=0; int posTemp = 0; int subStrLength = 1; int subStrL; while(posTemp != s.length()-1 ){ int posTempHead, posTempTail; if(s[posTemp] == s[posTemp+1]){ posTempHead = posTemp; posTempTail = posTemp+1; subStrL = 0; while(posTempHead >= 0 && posTempTail <= s.length()-1 && s[posTempHead] == s[posTempTail] ){ posTempHead--; posTempTail++; subStrL+=2; } if(subStrL>subStrLength){ posSubStrBegin = posTempHead+1; posSubStrEnd = posTempTail-1; subStrLength = subStrL; } } if(posTemp != 0 && s[posTemp-1] == s[posTemp+1]){ posTempHead = posTemp-1; posTempTail = posTemp+1; subStrL = 1; while(posTempHead >= 0 && posTempTail <= s.length()-1 && s[posTempHead] == s[posTempTail] ){ posTempHead--; posTempTail++; subStrL+=2; } if(subStrL>subStrLength){ posSubStrBegin = posTempHead+1; posSubStrEnd = posTempTail-1; subStrLength = subStrL; } } posTemp++; } res.assign(s, posSubStrBegin, subStrLength); return res; } };
leetcode - Longest Palindromic Substring
标签:
原文地址:http://www.cnblogs.com/shnj/p/4735314.html