这道题目和leetcode5 最长回文子串 是一样的。这里需要强调一点就是,C++中 string类中,substr(a,b) a是要截取字符串的起始坐标,b是指要截取字符串的长度。Java String类中 substring(a,b)中 a的含义一样,但是b是要截取字符串的尾坐标,这个和C++ string中 substr不一样,需要注意。
C++代码如下:
#include <iostream> #include <vector> #include <string> using namespace std; int longestPalindrome(string& s) { if (s.size() == 0) return 0; int start = 0; int maxLen = 0; int n = s.size(); vector<vector<bool>> d(n,vector<bool>(n,false)); for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { if (i == j) d[i][j] = true; else if (i + 1 == j) d[i][j] = s[i] == s[j]; else d[i][j] = ( s[i] == s[j] && d[i+1][j-1]); if (d[i][j] && (j - i + 1) > maxLen) { start = i; maxLen = j - i + 1; } } } return maxLen; } int main() { string s = ""; while (cin >> s) { cout << longestPalindrome(s) << endl; } return 0; }
原文:https://www.cnblogs.com/repinkply/p/13405625.html