- Leetcode-DP(Dynamic Programming)
- Leetcode--Longest Palindromic Su
- [LeetCode]5. Longest Palindromic
- LeetCode 5. Longest Palindromic
- LeetCode 5. Longest Palindromic
- LeetCode 5. Longest Palindromic
- LeetCode 5. Longest Palindromic
- [LeetCode]5. Longest Palindromic
- [Leetcode]5. Longest Palindromic
- LeetCode 5. Longest Palindromic
题目描述
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"
题目思路
题目是求出最长回文字符串,千万不要理解错题意啊
- 思路一、参考
class Solution {
public:
int maxLen = 0;
int start = 0;
string longestPalindrome(string s) {
int len = s.size();
if(len < 2) return s;
for(int i=0; i < len-1; i++){
fab(s, len, i, i); // 如果为奇数
fab(s, len, i, i+1); // 如果为偶数
}
return s.substr(start, maxLen);
}
void fab(string& s, int& len, int i, int j){
while(i >= 0 && j < len && s[i]==s[j]){
i--;
j++;
}
if(maxLen < j - i - 1){
maxLen = j - i - 1;
start = i+1;
}
}
};
![](https://img.haomeiwen.com/i11476842/5e75cb06e944c2cb.png)
- 思路二、
class Solution {
public:
int maxLen = 0;
int start = 0;
string longestPalindrome(string s) {
int len = s.size();
if(len < 2) return s;
int left = 0;
int right = 0;
for(int i=0; i < len; i++){
left = i;
right = i;
while(left >= 0 && s[left] == s[i]) left--;
while(right < len && s[right] == s[i]) right++;
while(left >= 0 && right < len && s[left] == s[right]){
left--;
right++;
}
if(maxLen < right-left-1){
maxLen = right - left - 1;
start = left + 1;
}
}
return s.substr(start, maxLen);
}
};
![](https://img.haomeiwen.com/i11476842/2ccf9b4aab24e11f.png)
- 思路三、multimap做的,耗时太多,因为超时,测试用例通过 101/103
class Solution {
public:
string longestPalindrome(string s) {
int len = s.size();
multimap<char, int> mp;
int maxstr = 1;
int start = 0;
int tt = 0;
// 判断是不是完全一样的字符串
int result = 0;
for(int i=0; i < len; i++){
if(s[i] == s[0]){
result += 1;
}
}
if(result == len) return s;
for(int i=0; i < len; i++){
// 找到了
if(mp.count(s[i]) > 0){
auto tt = mp.find(s[i]);
for(int k=0; k != mp.count(s[i]); k++,tt++){
// 构成回文字符串
if(fab(s, tt->second, i) == true){
if(maxstr < i - tt->second + 1){
maxstr = i - tt->second + 1;
start = tt->second;
}
}
}
}
mp.insert(make_pair(s[i], i));
}
return s.substr(start, maxstr);
}
bool fab(string& s, int i, int j){
while(i < j){
if(s[i++] != s[j--]){
return false;
}
}
return true;
}
};
网友评论