LeetCode 5_Longest Palindromic Substring
阿新 • • 發佈:2017-07-01
情況 ans log mil -i size ont enter ria
不用說,肯定超時。顯然暴力法有非常大的優化空間。在推斷子串的時候肯定有非常多反復的情況,能夠用一個表記錄已經推斷的情況!
上面的方法時間復雜度為O(n^2),能夠滿足題目的要求。
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. 也即:求字符串中最長回文子串。
回文是什麽我就不多少了。能夠百度下!
方法一:暴力法(O(n^3))
兩層循環掃描字符串的全部子串,之後推斷選出的字符子串是否是回文,若是則看其長度!
代碼例如以下:
class Solution { public: string longestPalindrome(string s) { // 暴力法O(n^3) int n = s.size(); if (n == 0 || n == 1) return s; int maxLength = 1; int k1 = 0, k2 = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int k = 0; int sign = 0; while (k < (j - i + 1)/2 && s[i + k] == s[j - k]) k++; if(k == (j - i + 1) / 2 ) { sign = 1; if (j - i + 1 > maxLength) { maxLength = j - i + 1; k1 = i; k2 = j; if (maxLength == n - i) return s.substr(k1,k2+1); } } } } return s.substr(k1,k2+1); }
因為題目說能夠假定字符串的長度不超過1000,所以建立一個table[1000][1000] 的bool表,初始化為false。如果某子串(如果 i 到 j )為回文。令table[ i ][ j ]為true。之後推斷的時候先查表和更新表。代碼例如以下:
class Solution { public: string longestPalindrome(string s) { int n = s.length(); if(n == 0 || n == 1) return s; int maxLength = 1; int palindromBegin = 0; bool table[1000][1000] = {false}; for(int i = 0; i < n; i++) table[i][i] = true; for (int i = 0; i < n; i++) if(s[i] == s[i + 1]) { table[i][i + 1] = true; maxLength = 2; palindromBegin = i; } for (int len = 3; len <= n ; len++) { for (int i = 0; i < n - len + 1; i++) { int j = i + len - 1; if (s[i] == s[j] && table[i + 1][j - 1] == true) { table[i][j] = true; maxLength = len; palindromBegin = i; } } } return s.substr(palindromBegin, maxLength); }
上面的方法時間復雜度為O(n^2),能夠滿足題目的要求。
事實上還能夠考慮回文的中心點。向兩邊擴展(回文的中心點能夠是摸個字符。也能夠是某兩個字符的中間),代碼例如以下:
string expandAroundCenter(string s, int c1, int c2) { int l = c1, r = c2; int n = s.length(); while (l >= 0 && r <= n-1 && s[l] == s[r]) { l--; r++; } return s.substr(l+1, r-l-1); } class Solution { public: string longestPalindrome(string s) { int n = s.length(); if (n == 0) return ""; string longest = s.substr(0, 1); // a single char itself is a palindrome for (int i = 0; i < n-1; i++) { string p1 = expandAroundCenter(s, i, i); if (p1.length() > longest.length()) longest = p1; string p2 = expandAroundCenter(s, i, i+1); if (p2.length() > longest.length()) longest = p2; } return longest; } };代碼的復雜度為O(n^2)。另一種說復雜度為O(n)的方法,只是我沒去看,有興趣的能夠看下: http://www.cnblogs.com/bitzhuwei/p/Longest-Palindromic-Substring-Part-II.html。
LeetCode 5_Longest Palindromic Substring