赞
踩
求一个字符串中的最长的回文子串
求一个字符串中的最长的回文子串
输出最长的回文子串
方法一:
#include<iostream> #include<vector> #include<string> using namespace std; class Solution { public: string longest(string s) { if (s.size() == 0) return s; int size = s.size(); vector<vector<int>> dp(size, vector<int>(size)); string ret = ""; int max = 0; for (int i = 0; i < size; i++) { for (int j = 0; j <= i; j++) { dp[i][j] = s[i] == s[j] && (i - j <= 2 || dp[i - 1][j + 1]); if (dp[i][j]) { if (i - j + 1>max) { max = i - j + 1; ret = s.substr(j, i -j + 1); } } } } return ret; } }; int main() { Solution sol; string s; cin >> s; cout << sol.longest(s) << endl; }
方法二:
#include<iostream> #include<vector> using namespace std; class Solution { public: string longest(string s) { if (s.size() < 2) return s; int length = s.size(); vector<vector<bool>> f(length, vector<bool>(length)); int maxlength = 1; int begin = 0; for (int i = 0; i < length; i++) { f[i][i] = true; } for (int j = 1; j < length; j++) { for (int i = 0; i < j; i++) { if (s[i] != s[j]) f[i][j] = false; else { if (j - i < 3) { f[i][j] = true; } else { f[i][j] = f[i + 1][j - 1]; } } if (f[i][j] && (j - i + 1) > maxlength) { maxlength = j - i + 1; begin = i; } } } return s.substr(begin, maxlength); } }; int main() { Solution sol; string s; cin >> s; cout << sol.longest(s) << endl; return 0; }
学习链接:最长回文子串学习链接
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。