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.
思路:如果不用动态规划,在两个for循环的情况下,还得依次比较i,j间的每个字符,O(n3)。使用动态规划,O(n2)
char* longestPalindrome(char* s) { int n = strlen(s); int max = 1; int pStart = 0; bool flag[n][n]; for(int i = 0; i < n; i++){ flag[i][i] = true; for(int j = i+1; j < n; j++){ flag[i][j] = false; } } for(int j = 1; j < n; j++){ //when iterate j, we should already iterated j-1, 可以理解成j之前已排序好=>用插入排序的顺序遍历 for(int i = 0; i < j; i++){ if(s[i]==s[j]){ flag[i][j] = (j==i+1)?true:flag[i+1][j-1]; if(flag[i][j] && j-i+1 > max){ max = j-i+1; pStart = i; } } } } s[pStart+max]='