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.
玩了两天dota2,罪过罪过,还是应该老老实实刷题啊。
题目求得是最长的回文子串,这里使用的是暴力的解法,也就是解决两种回文"asdsa"以及"assa",即奇数以及偶数回文,相当于用了二重循环,代码如下:
1 class Solution { 2 public: 3 string longestPalindrome(string s) { 4 if (!s.size()) return ""; 5 string ret; 6 string tmp; 7 for (int i = 0; i < s.size(); ++i){ 8 tmp = findPal(s, i - 1, i + 1); 9 if (tmp.size() > ret.size()) 10 ret = tmp; 11 tmp = findPal(s, i , i + 1); 12 if (tmp.size() > ret.size()) 13 ret = tmp; 14 } 15 return ret; 16 } 17 18 string findPal(string & s, int left, int right) 19 { 20 if (left < 0) 21 return s.substr(left + 1, 1); 22 if (right >= s.size()) 23 return s.substr(right - 1, 1); 24 25 while (left >= 0 && right < s.size()){ 26 if (s[left] != s[right]) 27 break; 28 left--; 29 right++; 30 } 31 left++; 32 return s.substr(left, right - left); 33 } 34 };
时间: 2024-12-28 07:41:38