leetcode647 回文子串
【摘要】
给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。
示例 1:
输入: "abc" 输出: 3 解释: 三个回文子串: "a", "b", "c". 示例 2:
输入: "aaa" 输出: 6 说明: 6个回文子串: "a", "a", "a", "aa", "aa", ...
给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。
示例 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;
-
}
-
}
文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。
原文链接:fantianzuo.blog.csdn.net/article/details/103299623
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)