5. Longest Palindromic Substring
Posted lychnis
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了5. Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。
5. Longest Palindromic Substring
Medium
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
1 class Solution { 2 int start; 3 int len; 4 public: 5 string longestPalindrome(string &s) { 6 if(s.size()<2)return s; //下面的循环处理不了空串和1个字符的串. 7 start=s.size(); 8 len=0; 9 for(int i=0;i<(int64_t)s.size()-1;++i) //这里需要注意的是 size返回的是64位无符号, 如果size为0, 这里将变为非常大的正数,导致无限循环超时,所以用int64_t , 巨坑 10 { 11 validatePalindrome(s,i,i); 12 validatePalindrome(s,i,i+1); 13 } 14 return s.substr(start,len); 15 } 16 17 void validatePalindrome(const string &s, int i, int j) 18 { 19 while(i>=0&&j<s.size()&&s[i]==s[j]) 20 { 21 --i; 22 ++j; 23 } 24 int l=j-i-1; 25 if(l<=len) 26 return; 27 start=i+1; 28 len=l; 29 } 30 };
以上是关于5. Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 5. Longest Palindromic Substring
5. Longest Palindromic Substring - Unsolved
5. Longest Palindromic Substring
5. Longest Palindromic Substring