题目:Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
给定一个字符串s,找到s中最长的回文子字符串。 您可以假设s的最大长度为1000
输入输出:
1. Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
2. Input: "cbbd" Output: "bb"
分析:题目是求字符串中最长回文串。我使用了两种解法,第一种暴力解法复杂度过高,超时了。第二种方法通过了。编译语言C++。
1. 首先写一个方法判断字符串是否为回文串,是返回true,否则返回false。
bool isPalin(string str){
int i=0;
int j = str.length()-1;
bool flag = true;
while(i<j){
if(str[i]!=str[j]){
flag = false;
break;
}
i++;
j--;
}
return flag;
}
暴力计算已知字符串s中的回文串,返回最长回文串。从字符串初始位置遍历所有子串,求出最长回文串。
#include <iostream>
#include<string>
#include<string.h>
using namespace std;
bool isPalin(string str){
int i=0;
int j = str.length()-1;
bool flag = true;
while(i<j){
if(str[i]!=str[j]){
flag = false;
break;
}
i++;
j--;
}
return flag;
}
int main()
{
string s;
cin>>s;
int maxNum = 1;
string str = s.substr(0,1);
for(int i=0;i<s.length();i++){
for(int j = i+1;j<=s.length();j++){
string sub = s.substr(i,j-i);
if(isPalin(sub)){
if(sub.length()>maxNum){
maxNum = sub.length();
str = sub;
}
}
}
}
cout << str << endl;
return 0;
}
2.第二种方法中心扩展,把字符串中每个字母作为字符中心,向两边扩展找到最长回文串。
这个需要考虑子回文串为奇数和偶数的情况。
#include <iostream>
#include<string>
#include<string.h>
using namespace std;
int main()
{
string s;
cin>>s;
int maxNum1 = 1;
string str1 = s.substr(0,1);
int maxNum2 = 1;
string str2 = s.substr(0,1);
for(int i=0;i<s.length();i++){
//考虑以i为中心回文串为偶数
int left1 = i;
int right1 = i+1;
while(left1>=0 && right1<s.length() && s[left1] == s[right1]){
if(right1-left1+1 > maxNum1){
maxNum1 = right1-left1+1;
str1 = s.substr(left1,right1-left1+1);
}
left1--;
right1++;
}
//考虑以i为中心回文串为奇数
int left2 = i-1;
int right2 = i+1;
while(left2>=0 && right2<s.length() && s[left2] == s[right2]){
if(right2-left2+1 > maxNum2){
maxNum2 = right2-left2+1;
str2 = s.substr(left2,right2-left2+1);
}
left2--;
right2++;
}
}
if(maxNum2>maxNum1){
str1 = str2;
}
cout << str1 << endl;
return 0;
}