Leetcode 5. Longest Palindromic Substring

個人解法是以每一個字符爲中心進行兩側試探,或者以每兩個相鄰字符爲中心進行兩側試探數組

public class Solution {
    public String longestPalindrome(String s) {
       int maxI = -1;
        int maxLengthI = 0;
        int maxJ = -1;
        int maxLengthJ = 0;
        for (int i = 0; i < s.length(); i++) {
            int p = i;
            int q = i;
            while (p >=0 && q < s.length()) {
                if (s.charAt(p) == s.charAt(q)) {
                    p--;
                    q++;
                } else {
                    break;
                }
            }
            if ((q-p-1) > maxLengthI) {
                maxLengthI = q-p-1;
                maxI = i;
            }
        }

        for (int j = 0; j< s.length()-1; j++) {
            int p = j;
            int q = j+1;
            while (p >=0 && q < s.length()) {
                if (s.charAt(p) == s.charAt(q)) {
                    p--;
                    q++;
                } else {
                    break;
                }
            }
            if ((q-p-1) > maxLengthJ) {
                maxLengthJ = q-p-1;
                maxJ = j;
            }
        }
        if (maxLengthI > maxLengthJ) {
            return s.substring(maxI - maxLengthI/2, maxI+maxLengthI/2+1);
        } else {
            return s.substring(maxJ - maxLengthJ/2+1, maxJ+maxLengthJ/2+1);
        }
    }
    
}

正統的方法還有動態規劃,動態規劃,相似於lcs的解法,數組flagi記錄s從i到j是否是迴文code

首先初始化,i>=j時,flagi=true,這是由於si是單字符的迴文,當i>j時,爲true,是由於有可能出現flag2這種狀況,好比bcaa,當計算s從2到3的時候,s[2]==s[3],這時就要計算s[2+1] ?= s[3-1],總的來講,當i>j時置爲true,就是爲了考慮j=i+1這種狀況。string

接着比較s[i] ?= s[j],若是成立,那麼flagi = flagi+1,不然直接flagi=falseio

class Solution {
public:
    string longestPalindrome(string s) {
        int len = s.length(), max = 1, ss = 0, tt = 0;
        bool flag[len][len];
        for (int i = 0; i < len; i++)
            for (int j = 0; j < len; j++)
                if (i >= j)
                    flag[i][j] = true;
                else flag[i][j] = false;
        for (int j = 1; j < len; j++)
            for (int i = 0; i < j; i++)
            {
                if (s[i] == s[j])
                {
                    flag[i][j] = flag[i+1][j-1];
                    if (flag[i][j] == true && j - i + 1 > max)
                    {
                        max = j - i + 1;
                        ss = i;
                        tt = j;
                    }
                }
                else flag[i][j] = false;
            }
        return s.substr(ss, max);
    }
};
相關文章
相關標籤/搜索