好的网站设计题目,手机如何编辑网页内容,室内设计学习,wordpress实现分享给定一个字符串#xff0c;你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串#xff0c;即使是由相同的字符组成#xff0c;也会被计为是不同的子串。
示例 1:
输入: abc 输出: 3 解释: 三个回文子串: a, …
给定一个字符串你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串即使是由相同的字符组成也会被计为是不同的子串。
示例 1:
输入: abc 输出: 3 解释: 三个回文子串: a, b, c. 示例 2:
输入: aaa 输出: 6 说明: 6个回文子串: a, a, a, aa, aa, aaa. 注意:
输入的字符串长度不会超过1000。
思路我一开始就想枚举每个中心往两边扩呗后来像动态规划一样是o(n*n)的看答案也没有更好的方法。
注意奇回文偶回文的问题
class Solution {public int countSubstrings(String s) {int count 0;for(int i 0; i s.length(); i){count countPalindrome(s, i, i);count countPalindrome(s, i, i 1);}return count;}public int countPalindrome (String s, int left, int right){int count 0;while(left 0 right s.length() s.charAt(left--) s.charAt(right))count;return count;}
}