leetcode 647. 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:

  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=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= 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;
}

你可能感兴趣的:(leetcode,leetcode)