【LeetCode】5. Longest Palindromic Substring
Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
同Palindrome Partitioning II 几乎一致,二维数组动态规划问题。
设置bool数组isPalin
isPalin[i][j]意为s[i...j]是否为回文字符串。
因此很容易找到递推关系:当s[i]==s[j]时
(1)如果i+1==j,或者
(2)如果isPalin[i-1][j+1]
那么isPalin[i][j]=true (此时与最大长度longest进行比较,并记录起始位置i)
否则isPalin[i][j]=false
提高效率需要注意两点:
1、使用数组比使用vector of vector节省时间;
2、每次发现当前最长回文串就使用substr取出会耗时间,改成记录开始位置和长度。
class Solution { public: string longestPalindrome(string s) { if(s == "" || s.size() == 1) return s; int size = s.size(); int begin = 0; int longest = 1; bool isPalin[1000][1000] = {false}; for(int i = 0; i < size; i ++) isPalin[i][i] = true; for(int i = size-2; i >= 0; i --) {//isPalin[size-1][size-1] has set to true for(int j = i+1; j < size; j ++) {//isPalin[i][i] has set to true //check whether s[i...j] is a palindrome if(s[i] == s[j]) { if(j == i+1 || isPalin[i+1][j-1]) {//case1: j is next to i //case2: s[i+1...j-1] is a palindrome isPalin[i][j] = true; if(j-i+1 > longest) { longest = j-i+1; begin = i; } } } } } return s.substr(begin, longest); } };