[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.
用一个指针从0遍历到s.size()-1,从里向外来检测子串是否是回文,分两种情况:1)bab, 2)bb。也就是当前指针可能指向的是奇数回文,也可能是偶数回文。做两次检测。
1 class Solution { 2 public: 3 string findPal(string &s, int left, int right) 4 { 5 if (left < 0) 6 return s.substr(left+1, 1); 7 8 if (right >= s.size()) 9 return s.substr(right-1, 1); 10 11 while(0 <= left && right < s.size()) 12 { 13 if (s[left] != s[right]) 14 break; 15 left--; 16 right++; 17 } 18 19 left++; 20 right--; 21 22 return s.substr(left, right - left + 1); 23 } 24 25 string longestPalindrome(string s) { 26 // Start typing your C/C++ solution below 27 // DO NOT write int main() function 28 if (s.size() == 0) 29 return ""; 30 31 string ret; 32 33 for(int i = 0; i < s.size(); i++) 34 { 35 string str = findPal(s, i - 1, i + 1); 36 if (str.size() > ret.size()) 37 ret = str; 38 39 str = findPal(s, i, i + 1); 40 if (str.size() > ret.size()) 41 ret = str; 42 } 43 44 return ret; 45 } 46 };