O(n^3)时间复杂度方法——暴力求解
1.思想:
1)从最短的子串开始,遍历所有该原字符串的子串;
2)每找出一个字符串,就判断该字符串是否为回文;
3)子串为回文时,则找到了最长的回文子串,因此结束;反之,则继续遍历。
//采用暴力的方式进行求解
class Solution {
public:
string isPalindrome(string s)
{
string temp=s;
reverse(s.begin(), s.end());
if ( temp == s)
return temp;
else
return "";
}
string longestPalindrome(string s) {
int length =0;
string res="" ;
string sub;
int num = s.size();
if( num<=1)
return s;
for (int i = 0 ; i < num ;i++)
{
for( int j=i+1; j<num ;j++)
{
sub =s.substr(i,j);
// 判断子串是不是回文字符
string temp=isPalindrome(sub);
//cout<<"temp:"<<temp<<endl;
//length =temp.size();
if(length< temp.size() )
{
res=temp;
length = res.size();
}// 更新长度
}
}
return res;
}
};
int main() {
cout<<(Solution().longestPalindrome("a"))<<endl;
cout<<(Solution().longestPalindrome("abd"))<<endl;
cout<<(Solution().longestPalindrome("aa"))<<endl;
cout<<(Solution().longestPalindrome("cabacabbbbba"))<<endl;
cout<<(Solution().longestPalindrome("a"))<<endl;
return 1;
}