题目
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.
答案
一道动规题目,每次用当前位置columnIndex跟前面位置rowIndex去比较时,如果相同的话,就去看columnIndex- 1和rowIndex+1字母的状态,其实在走到columnIndex时,columnIndex-1和它自己前面的字母是比较过了的,将这个状态记下来就行。
讲真,我这代码效率不高,应该还有其他思路,再想想。
代码
1 #define MAX_LENGTH 1001 2 class Solution { 3 public: 4 string longestPalindrome(string s) { 5 if(s.empty()) 6 { 7 return string(""); 8 } 9 bool charRelFlag[MAX_LENGTH][MAX_LENGTH]; 10 int sLen = s.size(); 11 int subStart = 0; 12 int subEnd = 0; 13 int rowIndex,columnIndex; 14 15 for(rowIndex = 0; rowIndex < sLen; ++ rowIndex) 16 { 17 charRelFlag[rowIndex][rowIndex] = true; 18 for(columnIndex = rowIndex + 1; columnIndex < sLen; ++ columnIndex) 19 { 20 charRelFlag[rowIndex][columnIndex] = false; 21 } 22 } 23 24 int maxLen = 1; 25 for(columnIndex = 1; columnIndex < sLen; ++ columnIndex) 26 { 27 for(rowIndex = 0; rowIndex < columnIndex; ++ rowIndex) 28 { 29 if(s[rowIndex] == s[columnIndex]) 30 { 31 if(rowIndex + 1 == columnIndex) 32 { 33 charRelFlag[rowIndex][columnIndex] = true; 34 if(maxLen < 2) 35 { 36 maxLen = 2; 37 subStart = rowIndex; 38 subEnd = columnIndex; 39 } 40 }else 41 { 42 if(charRelFlag[rowIndex + 1][columnIndex - 1] == true) 43 { 44 charRelFlag[rowIndex][columnIndex] = true; 45 if(maxLen < columnIndex - rowIndex + 1) 46 { 47 maxLen = columnIndex - rowIndex + 1; 48 subStart = rowIndex; 49 subEnd = columnIndex; 50 } 51 } 52 } 53 54 } 55 } 56 } 57 58 return s.substr(subStart,maxLen); 59 } 60 };