leetcode 647:回文子串的个数

leetcode 647:回文子串的个数


题目描述:给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
解题步骤:这个题与求最长回文子串类似,只需要将每个子串是否为回文求出来在判断,通过动态规划求解
代码

    public int longestPalindrome(String s) {
    	int n = s.length();
    	int count = 0;
    	boolean[][] dp = new boolean[n][n];
    	for (int i = n-1; i >= 0; i--) {
			dp[i][i] = true;
			for (int j = i; j < n; j++) {
				if(s.charAt(i) == s.charAt(j)) {
					dp[i][j] = true&&(j-i<3||dp[i+1][j-1]);
					if(dp[i][j])
						count++;
				}
				else {
					dp[i][j] = false;
				}
			}
		}
    	for (int i = 0; i < dp.length; i++) {
			System.out.println(Arrays.toString(dp[i]));
		}
    	return count;
    }
发布了28 篇原创文章 · 获赞 0 · 访问量 251

猜你喜欢

转载自blog.csdn.net/zy450271923/article/details/105301366