題目ide
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.spa
答案code
一道動規題目,每次用當前位置columnIndex跟前面位置rowIndex去比較時,若是相同的話,就去看columnIndex- 1和rowIndex+1字母的狀態,其實在走到columnIndex時,columnIndex-1和它本身前面的字母是比較過了的,將這個狀態記下來就行。blog
講真,我這代碼效率不高,應該還有其餘思路,再想一想。string
代碼io
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 };