Palindromic Substrings

来源:互联网 发布:李宁淘宝旗舰店 编辑:程序博客网 时间:2024/06/05 08:53

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: 3Explanation: Three palindromic strings: "a", "b", "c".Example 2:Input: "aaa"Output: 6Explanation: 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++;        }    }
原创粉丝点击