最长回文子串-暴力-不用manacher
题目描述
给你一个字符串 s,找到 s 中最长的回文子串。
示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。
示例 2:
输入:s = “cbbd”
输出:“bb”
示例 3:
输入:s = “a”
输出:“a”
示例 4:
输入:s = “ac”
输出:“a”
解题思路
暴力法:
(1)首先考虑遍历字符串的所有子串,对每个遍历到的子串做一次判断是否为回文的操作。
(2)建一个空的有序map,key存储每个子串的长度,value存储该子串。
(3)当该子串被判断为回文串时,将该子串及其长度存入map中,所有子串按照其长度在map中被存储。
(4)返回map中最后一个元素的value,即为最长子串。
class Solution { public: string longestPalindrome(string s) { if(s.size()== 0) return ""; //if(s.size() == 1) return s[0]; //建一个用于保存长度和对应回文子串的有序map map<int, string>substr_count; //遍历所有子串 for(int i = 0; i < s.size(); i++){ for(int j = i; j < s.size(); j++){ string temp = s.substr(i, j-i+1); //substr()函数 //如果子串是回文的,存入map if(isPalind(temp)){ substr_count.insert({temp.size(), temp}); } } } //返回map中最后一个元素的value map<int, string>::iterator iter; iter = substr_count.end(); iter--; return iter->second; } //一个判断是否回文的函数 bool isPalind(string s){ if(s.size() == 1){ return true; } int head = 0; int tail = s.size()-1; while(head <= tail){ //限制调节做的很好 if(s[head] == s[tail]){ head++; tail--; } else{ return false; } } return true; } };
substr substr是C++语言函数,主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。
如果没有指定长度_Count或_Count+_Off超出了源字符串的长度,则子字符串将延续到源字符
串的结尾。
basic_string substr(size_type _Off = 0,size_type _Count = npos) const;
#include<string> #includeusing namespace std; int main() { string s("12345asdf"); string a = s.substr(0,5); //获得字符串s中从第0位开始的长度为5的字符串 cout << a << endl; }
//12345