Palindromic Substrings

Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
The input string length won't exceed 1000.

題解:大意就是找一個字符串中所有迴文子串的個數。這裏用動態規劃,狀態定義dp[i][j]表示字符串s[i]到s[j]的子串是否爲迴文,dp[i][j]=dp[i+1][j-1]&&s[i]==s[j] 從狀態轉移方程來開,只需要我們從下往上,從左往右遍歷即可。

代碼:

    public static int countSubstrings(String s) {

        if (s == null || s.length() <2)
            return s.length()==1? 1: 0;

        int n = s.length();
        boolean[][] dp = new boolean[n][n];


        for (int i = 0; i < n;i++)
        {
            dp[i][0] = true;
            dp[n-1][i] =true;
        }
        int count = 2;                  
        //字符串頭尾兩個單字符迴文,即對角線上已經被初始化的兩個

        for (int i = n - 2; i >= 0; i--)
            for (int j = 1; j < n; j++) {
                if (i > j)
                    dp[i][j] = true;
                else {
                    dp[i][j] = dp[i + 1][j - 1] && (s.charAt(i) == s.charAt(j));
                    count += dp[i][j] == true ? 1 : 0;
                }
            }

        return count;
    }

迴文另一種解法:找中心點,然後往兩邊擴展判斷是否相等,是否爲迴文。通過遍歷以i爲中心(奇數)或i和i+1(偶數),迴文長度爲奇數和偶數,遍歷所有可能的中心點,查找回文的個數

     int count = 0;

    public int better_countSubstrings(String s) {
        if (s == null || s.length() == 0) return 0;

        for (int i = 0; i < s.length(); i++) { // i is the mid point
            extendPalindrome(s, i, i); // odd length;
            extendPalindrome(s, i, i + 1); // even length
        }

        return count;
    }

    private void extendPalindrome(String s, int left, int right) {
        while (left >=0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            count++; left--; right++;
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章