leetcode 647. Palindromic Substrings

257 篇文章 17 订阅

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值