天天看點

LeetCode647回文子串

給定一個字元串,你的任務是計算這個字元串中有多少個回文子串。

具有不同開始位置或結束位置的子串,即使是由相同的字元組成,也會被視作不同的子串。

示例 1:

輸入:"abc" 輸出:3 解釋:三個回文子串: "a", "b", "c"

示例 2:

輸入:"aaa" 輸出:6 解釋:6個回文子串: "a", "a", "a", "aa", "aa", "aaa"

提示:

輸入的字元串長度不會超過 1000 。

先暴力解決

class Solution {
    public int countSubstrings(String s) {
        int count = 0;
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            for (int j = i; j < chars.length; j++) {
                if (isTrue(s.substring(i, j+1)) == true)
                    count++;
            }
        }
        return count;
    }
    private static boolean isTrue(String s) {
        char[] chars = s.toCharArray();//将字元串轉化為字元數組
        for (int i = 0, j = chars.length - 1; i <= j; i++, j--) {
            if (chars[i] != chars[j]) {
                return false;
            }
        }
        return true;
    }
}
           
LeetCode647回文子串

雖然通過了,但是效率很差,接下來想想怎麼優化…

使用動态規劃

class Solution {
    public int countSubstrings(String s) {
        if(s == null || s.equals("")){
            return 0;
        }

        int n = s.length();

        boolean[][] dp = new boolean[n][n];

        int result = s.length();

        for(int i = 0; i<n; i++)
            dp[i][i] = true;
        
        for(int i = n-1; i>=0; i--){
            for(int j = i+1; j<n; j++){
                if(s.charAt(i) == s.charAt(j)) {
                    if(j-i == 1){
                        dp[i][j] = true;
                    }
                    else{
                        dp[i][j] = dp[i+1][j-1];
                    }
                }else{
                    dp[i][j] = false;
                }
                if(dp[i][j]){
                    result++;
                }
            }
        }
        return result;
    }
   
}