Leetcode647. 计算回文子字符串数目
2017-09-29 23:38
190 查看
Leetcode647. Palindromic Substrings
题目
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”.
解题分析
一拿到这道题,可能第一想法就是感觉这道题好麻烦呀,需要找出该字符串的所有子字符串,再分别对这些子字符串进行判断。的确,和我们的感觉一样,这样的做法确实是很普通的,虽然可以AC,但时间复杂度太大了,为O(n^3)。那么有没有更好的做法呢?其实是有的。我们可不可以这样想,在遍历字符串的时候,考虑一下对每个字符进行左右扩展?(比如aaa,对中间的a进行左右扩展得到aaa)这样的话,就不需要再找子字符串再进行判断了,我们只需在遍历的时候,对每个字符的左方和右方的字符进行判断,如果相同就继续往两侧扩展直到一方到达该字符串的边界;如果不同,则直接结束循环,这样时间复杂度就有效地变成O(n^2)了。
但其实上面这样做的话只考虑到了字符串长度为奇数的情况,偶数的情况没有考虑(比如aa)。但其实做法跟上面完全相同,这里我就不再细述了。两种情况相加,就是最后的结果。
源代码
class Solution { public: int count = 0; int countSubstrings(string s) { int i, size = s.size(); for (i = 0; i < size; i++) { extend(s, i, i); extend(s, i, i + 1); } return count; } void extend(string s, int left, int right) { while (left >= 0 && right < s.size() && s[left] == s[right]) { count++; left--; right++; } } };
以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~
相关文章推荐
- 计算在已知字符串中所有回文子序列的数目
- 计算字符串的最长回文子序列
- 93.计算字符串s中所包含t字符串的数目
- 算法基础(三)---- 计算字符串数字平均值
- iOS7中计算UILabel中字符串的高度
- 在Java中计算四则运算表达式字符串的值
- 计算字符串长度
- 计算字符串问题
- Leetcode712. 计算两个字符串删除任意字符后使二者相等的最小删除字符和
- python计算一段字符串字母的和(a,b分别为1,2)
- [算法 笔记]字符串表达式计算(简易版)
- Asp.Net 利用TimeSpan类实现时间差计算 并返回所需字符串(类似于SNS)
- 02 计算字符串表达式 [类似于js eval函数]
- Shell脚本中计算字符串长度的5种方法
- iOS根据字符串计算UITextView高度
- 计算字符串出现的次数
- C语言:(旧)用字符串自由输入计算的计算器(加减乘除)
- 计算组合数据的数目
- 最长回文子字符串
- 【华为OJ】【078-计算字符串的距离】