1. 程式人生 > 其它 >兩個迴文子序列長度的最大乘積--java

兩個迴文子序列長度的最大乘積--java

給你一個字串s,請你找到s中兩個不相交回文子序列,使得它們長度的乘積最大。兩個子序列在原字串中如果沒有任何相同下標的字元,則它們是不相交的。

請你返回兩個迴文子序列長度可以達到的最大乘積。

子序列指的是從原字串中刪除若干個字元(可以一個也不刪除)後,剩餘字元不改變順序而得到的結果。如果一個字串從前往後讀和從後往前讀一模一樣,那麼這個字串是一個 迴文字串。

示例 1:

輸入:s = "leetcodecom"
輸出:9
解釋:最優方案是選擇 "ete" 作為第一個子序列,"cdc" 作為第二個子序列。
它們的乘積為 3 * 3 = 9 。
示例 2:

輸入:s = "bb"
輸出:1
解釋:最優方案為選擇 "b" (第一個字元)作為第一個子序列,"b" (第二個字元)作為第二個子序列。
它們的乘積為 1 * 1 = 1 。
示例 3:

輸入:s = "accbcaxxcxx"
輸出:25
解釋:最優方案為選擇 "accca" 作為第一個子序列,"xxcxx" 作為第二個子序列。
它們的乘積為 5 * 5 = 25 。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

class Solution {
    int cnt = 0;    //記錄迴文乘積

    public int maxProduct(String s) {
        String s1 = new String();
        String s2 = new String();
        dfs(s,s1,s2,0);
        return cnt; //返回迴文乘積
    }

    void dfs(String s , String s1 ,String s2 ,int index){
        if(check(s1) && check(s2)) 
            cnt = Math.max(cnt , s1.length() * s2.length()  ); //把最大的迴文乘積給到cut
        if(index == s.length()) return; //排除特殊情況
        dfs(s ,s1 + s.charAt(index) ,s2 , index + 1 );  //遞迴使用check函式找到s1的迴文
        dfs(s ,s1 ,s2 + s.charAt(index) , index + 1 );  //遞迴使用check函式找到s2的迴文
        dfs(s ,s1 ,s2 , index + 1 );
    }
    boolean check(String s){    //判斷是否迴文,找到迴文的字串
        int l = 0 ,r = s.length() - 1;
        while(l<r){
            if(s.charAt(l) != s.charAt(r)){     //不是迴文結束
                return false;
            } 
            l++;
            r--;
        }
        return true;
    }
}