leetcode 647. Palindromic Substrings

来源:互联网 发布:windows server 10 编辑:程序博客网 时间:2024/05/16 11:56

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:

  1. The input string length won't exceed 1000.
这道题用DP的话蛮容易的,思路比较好想。DP[ i ][ j ] 存储 index 从 i ~ j 是不是回文。

public int countSubstrings(String s) {if(s.equals("")){return 0;}int count=0;char[] cs=s.toCharArray();int n=cs.length;boolean DP[][]=new boolean[n][n];for(int i=0;i<n;i++){DP[i][i]=true;}count+=n;for(int len=1;len<n;len++){for(int i=0;i<n-len;i++){int j=i+len;if(cs[i]!=cs[j]){DP[i][j]=false;}else{DP[i][j]=ifHuiWen(DP, i+1, j-1);if(DP[i][j]==true){count++;}}}}return count;}public boolean ifHuiWen(boolean DP[][],int i,int j){if(i>=j){return true;}else{return DP[i][j];}}

大神想到了一个不用DP的方法:

思路是 考虑不同的回文中心,然后从中心扩大,求以某个中心来获得的回文个数。
有两种情况:子串 s[ i - j , ...,  i + j ] 中, i 是回文中心(这是奇数串的情形)。子串 s[ i - 1 - j , ...,  i + j ] 中,( i - 1 , i ) 是回文中心(这是偶数串的情形)。

public int countSubstrings(String s) {    int res = 0, n = s.length();    for(int i = 0; i<n ;i++ ){        for(int j = 0; i-j >= 0 && i+j < n && s.charAt(i-j) == s.charAt(i+j); j++){        res++; //substring s[i-j, ..., i+j]        }        for(int j = 0; i-1-j >= 0 && i+j < n && s.charAt(i-1-j) == s.charAt(i+j); j++){        res++; //substring s[i-1-j, ..., i+j]        }    }    return res;}

原创粉丝点击