从零开始的CPP(23)动态规划解决最长回文串
leetcode5
给你一个字符串 s
,找到 s
中最长的
回文串
示例 1:
输入:s = "babad" 输出:"bab" 解释:"aba" 同样是符合题意的答案。
最开始我是将回文串都存入map。使用substr进行切割,i为起始,j-i+1是步长
string longestPalindrome(string s) {
if (s.length() <= 1) {
return s;
}
map<int,string> resultmap;
string temp;
for (int i = 0; i < s.length() - 1; i++) {
for (int j = i; j < s.length(); j++) {
//cout << "temp:" << temp << endl;
string s1 = s.substr(i, j-i+1);
temp = s1;
reverse(temp.begin(), temp.end());
//cout << "s1:" << s1 << endl;
if (temp == s1) {
resultmap[i] = s1;
//cout << "s1:" << s1 << endl;
}
}
}
int length = 0;
int index = 0;
for (int i = 0; i < resultmap.size(); i++) {
if (resultmap[i].length() > length) {
length = resultmap[i].length();
index = i;
}
}
return resultmap[index];
}
优化了一下,还是时间复杂度高
string longestPalindrome(string s) {
if (s.length() <= 1) {
return s;
}
//map<int,string> resultmap;
string temp;
int max = 0;
string maxstr;
for (int i = 0; i < s.length() - 1; i++) {
for (int j = i; j < s.length(); j++) {
string s1 = s.substr(i, j - i + 1);
temp = s1;
if (s1.length() > max){
reverse(temp.begin(), temp.end());
//cout << "s1:" << s1 << endl;
//cout << "temp:" << temp << endl;
if (temp == s1) {
maxstr = s1;
max = s1.length();
//cout << "s1:" << s1 << endl;
}
}
}
}
return maxstr;
}
最终还是用动态规划的方式解决。动态规划的核心思想把已经发生过的情况储存起来,需要时直接调用,也就是空间换时间。
dp存储了某一段字符串是否是回文串,dp[i][j]
的值如果为true
,表示字符串s
中从下标i
到下标j
的子串是一个回文串;如果为false
,则不是回文串。
动态规划需要递推,所以也需要初始化,这里需要初始化单个字符串与连续字符串的情况,之后递推。
string longestPalindrome(string s) {
int n = s.length();
if (n <= 1) {
return s;
}
vector <vector<bool>> dp(n, vector<bool>(n, false));
for (int i = 0; i < s.length(); i++) {
dp[i][i] = true;
}
for (int i = 0; i < s.length()-1; i++) {
if (s[i]==s[i+1])
{
dp[i][i+1] = true;
dp[i+1][i] = true;
}
}
int index=0;
int maxlen=0;
for (int len = 1; len < s.length(); len++) {
for (int j = 0; j + len < s.length(); j++) {
//cout << s[j] << endl << s[j + len]<<endl;
if (s[j] == s[j + len] && dp[j + 1][j + len - 1]==true) {
dp[j][j + len] = true;
dp[j+len][j] = true;
index = j;
maxlen = len;
cout << "找到回文" << ":";
cout << index << "," << maxlen;
}
}
}
string res = s.substr(index, maxlen+1);
return res;
}
原文地址:https://blog.csdn.net/m0_69248655/article/details/140566999
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!