赞
踩
给定一个字符串 s
,请计算这个字符串中有多少个回文子字符串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
输入:s = "abc"
输出:3
解释:三个回文子串: "a", "b", "c"
输入:s = "aaa"
输出:6
解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
提示:
1 <= s.length <= 1000
s
由小写英文字母组成1.用一个二维数组去存储当前的位置是不是回文字符串
2.如果当前位置头尾相同并且里面是回文串,那当前i到j就是回文串
3.chars[i]==chars[j]&&(i-j<=1||dp[j+1][i-1])
4.还有一种方法就是中心扩散法,就是遍历每个位置,然后由中心向两边扩散
// 动态规划 class Solution { public boolean validPalindrome(String s) { char[] chars = s.toCharArray(); int left = 0,right = chars.length-1; int cnt = 1; while(left<right) { if(chars[left]!=chars[right]) { return isEcho(chars,left+1,right)||isEcho(chars,left,right-1); } left++; right--; } return true; } public boolean isEcho(char[] chars,int l ,int r) { while(l<r) { if(chars[l]!=chars[r]) return false; l++; r--; } return true; } }
// 中心扩散法 class Solution { public int countSubstrings(String s) { int len = s.length(); char[] chars = s.toCharArray(); int res = 0; for(int i = 0;i<len;i++) { res +=countEcho(chars,i,i); res +=countEcho(chars,i,i+1); } return res; } public int countEcho(char[] chars,int left,int right) { int res = 0; while(left>=0&&right<chars.length) { if(chars[left--]==chars[right++]) res++; else break; } return res; } }
欢迎大佬们关注小弟的博客https://blog.csdn.net/qq_41522089
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。