[*leetcode 5] 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.
[Solution]
求最長回文子串,假設我們已知S[i...j]是回文子串,那么,若S[i-1] = S[j+1],則S[i-1,...,j+1]是回文子串。
1、雙指針法
用middle順序指向S中的字符,如果S[left] == S[right], 那么left和right分別向兩邊擴展。
1 string longestPalindrome(string s) 2 { 3 int left = 0, right = 0, middle = 0, slen = s.size(); 4 string result = ""; 5 6 while (middle < slen) 7 { 8 left = right = middle; 9 while ((left > 0) && (s[left - 1] == s[middle])) 10 left--; 11 while ((right < slen - 1) && (s[right + 1] == s[middle])) 12 right++; 13 while ((left > 0) && (right < slen - 1) && (s[left - 1] == s[right + 1])) 14 left--, right++; 15 16 if (result.size() < (right - left + 1)) 17 result = s.substr(left, right - left + 1); 18 middle++; 19 } 20 21 return result; 22 }2、動態規劃
用table[i][j]的true/false表示S[i,...,j]是否為回文子串,
可以得到遞推公式:table[i][j] = table[i+1][j-1] && (S[i] == S[j]) (i+1 <= j-1, 即 i+2 <= j)
初始條件:
當j = i 時,table[i][j] = true;
當j = i + 1時,table[i][j] = (S[i] == S[j])
1 string longestPalindrome(string s) 2 { 3 bool table[1000][1000] = {false}; 4 int i, j, slen = s.length(), start = 0, maxlen = 1; 5 6 for (i = 0; i < slen; i++) 7 table[i][i] = true; 8 for (i = 0; i < slen - 1; i++) 9 { 10 j = i + 1; 11 if (s[i] == s[j]) 12 { 13 table[i][j] = true; 14 start = i; 15 maxlen = 2; 16 } 17 } 18 19 for (int len = 3; len <= slen; len++) 20 { 21 for (i = 0; i < slen - len + 1; i++) 22 { 23 j = i + len - 1; 24 if (s[i] == s[j] && table[i + 1][j - 1]) 25 { 26 table[i][j] = true; 27 start = i; 28 maxlen = len; 29 } 30 } 31 } 32 33 return s.substr(start, maxlen); 34 }?
轉載于:https://www.cnblogs.com/ym65536/p/4207123.html
總結
以上是生活随笔為你收集整理的[*leetcode 5] Longest Palindromic Substring的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构之栈的应用:树的层次遍历、图的广
- 下一篇: (王道408考研操作系统)第四章文件管理