LeetCode 5. Longest Palindromic Substring
https://leetcode.com/problems/longest-palindromic-substring/description/
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
- 最长回文子串。字符串处理题。可以深搜,动规,不过还是这个算法比较简单明了,找到回文串然后向两边扩张。
1 // 2 // main.cpp 3 // LeetCode 4 // 5 // Created by Hao on 2017/3/16. 6 // Copyright © 2017年 Hao. All rights reserved. 7 // 8 9 #include <iostream> 10 #include <string> 11 using namespace std; 12 13 class Solution { 14 public: 15 string longestPalindrome(string s) { 16 if (s.empty()) return ""; 17 if (s.size() == 1) return s; 18 19 size_t start = 0, maxLen = 1; 20 21 for (size_t i = 0; i < s.size(); ) { 22 if (s.size() - i <= maxLen / 2) break; 23 size_t j = i, k = i; 24 25 // Duplicate characters 26 while ((k < s.size() - 1) && (s[k] == s[k + 1])) k ++; 27 28 // Move start pointer 29 i = k + 1; 30 31 // Expand 32 while ((k < s.size() - 1) && (j > 0) && (s[k + 1] == s[j - 1])) { 33 k ++; 34 j --; 35 } 36 37 if (k - j + 1 > maxLen) { 38 maxLen = k - j + 1; 39 start = j; 40 } 41 } 42 43 return s.substr(start, maxLen); 44 } 45 }; 46 47 int main () 48 { 49 Solution testSolution; 50 string sTest[] = {"babad", "cbbd"}; 51 52 for (int i = 0; i < 2; i ++) 53 cout << testSolution.longestPalindrome(sTest[i]) << endl; 54 55 return 0; 56 }
- Python算法同上,注意slicing左闭右开。
1 class Solution: 2 def longestPalindrome(self, s: str) -> str: 3 if not s: 4 return "" 5 6 if len( s ) == 1: 7 return s 8 9 n_s = len( s ) 10 start, maxlen = 0, 1 11 i = 0 12 13 while i < n_s: 14 if n_s - i <= maxlen / 2: 15 break; 16 17 left = right = i 18 19 # move right point as duplicate chars is the center of palindromic substring 20 while ( right + 1 < n_s ) and ( s[ right ] == s[ right + 1 ] ): 21 right += 1 22 23 # start point of next loop 24 i = right + 1 25 26 # expand left and right points 27 while ( left > 0 ) and ( right + 1 < n_s ) and ( s[ left - 1 ] == s[ right + 1 ] ): 28 left -= 1 29 right += 1 30 31 if right - left + 1 > maxlen: 32 maxlen = right - left + 1 33 start = left 34 35 # pay attention to slicing 36 return s[ start : start + maxlen ]