leetcode: Longest Palindromic Substring
http://oj.leetcode.com/problems/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.
思路:
这题有牛B的算法,大家可以自己Google。这里用一种比较简单的算法,虽然不够快但是也能过OJ。如果一个字符串已经是回文字符串,向左右扩展,如果两个新增加的字母相同,那么扩展后的字符串也是回文。奇数偶数情况分别处理即可。
1 class Solution { 2 public: 3 int extend(const string &s, int start, int end) { 4 int len = s.length(), steps = 0; 5 6 while ((start >= 0) && (end < len)) { 7 if (s[start] == s[end]) { 8 --start; 9 ++end; 10 ++steps; 11 } 12 else { 13 break; 14 } 15 } 16 17 return steps; 18 } 19 20 string longestPalindrome(string s) { 21 int start = 0, max = 0; 22 23 for (int i = 0; i < s.length(); ++i) { 24 int steps, sub_len; 25 26 steps = extend(s, i, i + 1); 27 sub_len = steps * 2; 28 29 if (sub_len > max) { 30 start = i - steps + 1; 31 max = sub_len; 32 } 33 34 steps = extend(s, i - 1, i + 1); 35 sub_len = steps * 2 + 1; 36 37 if (sub_len > max) { 38 start = i - steps; 39 max = sub_len; 40 } 41 } 42 43 return s.substr(start, max); 44 } 45 };