作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/palindromic-substrings/description/

题目描述

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".

Note:

  1. The input string length won’t exceed 1000.

题目大意

判断子字符串有多少个回文。

解题方法

方法一:暴力循环

看到字符的长度只有1000,首先用暴力解法。双重循环,得到所有的子字符串,然后判断是不是回文。

时间复杂度基本是O(N^3),超过1%的提交。

代码:

class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
count = 0
for i in xrange(len(s)):
for j in xrange(i, len(s)):
if s[i:j + 1] == s[i:j + 1][::-1]:
count += 1
return count

方法二:固定起点向后找

index从0到len进行遍历。对于每个单个的字符,其本身是一个回文。然后对回文长度是奇数的情况进行遍历:使用left和right双指针,往两边走,判断总长度是3,5,7……的子串是不是回文(left指针和right指针指向的字符相等)。再对回文是偶数的情况同样的进行遍历。最后求和即可。

比较巧妙的一种思想,不要怕代码长,其实没啥。

class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
count = 0
for i in xrange(len(s)):
count += 1
#回文长度是奇数的情况
left = i - 1
right = i + 1
while left >= 0 and right < len(s) and s[left] == s[right]:
count += 1
left -= 1
right += 1
#回文长度是偶数的情况
left = i
right = i + 1
while left >= 0 and right < len(s) and s[left] == s[right]:
count += 1
left -= 1
right += 1
return count

方法三:动态规划

动态规划的思想是,我们先确定所有的回文,即 string[start:end]是回文. 当我们要确定string[i:j] 是不是回文的时候,要确定:

  1. string[i] 等于 string[j]吗?
  2. string[i+1:j-1]是回文吗?

单个字符是回文;两个连续字符如果相等是回文;如果有3个以上的字符,需要两头相等并且去掉首尾之后依然是回文。

Python代码如下:

class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
count = 0
start, end, maxL = 0, 0, 0
dp = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(i):
dp[j][i] = (s[j] == s[i]) & ((i - j < 2) | dp[j + 1][i - 1])
if dp[j][i]:
count += 1
dp[i][i] = 1
count += 1
return count

二刷的Python代码如下:

class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
count = 0
N = len(s)
dp = [[False] * N for _ in range(N)]
for l in range(1, N + 1): # step size
for i in range(N - l + 1):
j = i + l - 1
if l == 1 or (l == 2 and s[i] == s[j]) or (l >= 3 and s[i] == s[j] and dp[i + 1][j - 1]):
dp[i][j] = True
count += 1
return count

C++代码如下:

class Solution {
public:
int countSubstrings(string s) {
const int N = s.size();
vector<vector<int>> dp(N, vector<int>(N, false));
int count = 0;
for (int l = 1; l <= N; l ++) {
for (int i = 0; i <= N - l; i ++) {
int j = i + l - 1;
if (l == 1 || (l == 2 && s[i] == s[j]) || (l >= 3 && s[i] == s[j] && dp[i + 1][j - 1])) {
count ++;
dp[i][j] = true;
}
}
}
return count;
}
};

日期

2018 年 3 月 3 日
2018 年 12 月 10 日 —— 又是周一!

【LeetCode】647. Palindromic Substrings 解题报告(Python & C++)的更多相关文章

  1. 【LeetCode】647. Palindromic Substrings 解题报告(Python)

    [LeetCode]647. Palindromic Substrings 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/p ...

  2. [LeetCode] 647. Palindromic Substrings 回文子字符串

    Given a string, your task is to count how many palindromic substrings in this string. The substrings ...

  3. Leetcode 647. Palindromic Substrings

    Given a string, your task is to count how many palindromic substrings in this string. The substrings ...

  4. LeetCode 647. Palindromic Substrings的三种解法

    转载地址 https://www.cnblogs.com/AlvinZH/p/8527668.html#_label5 题目详情 给定一个字符串,你的任务是计算这个字符串中有多少个回文子串. 具有不同 ...

  5. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  6. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  7. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  8. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

  9. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

随机推荐

  1. zabbix 内网机器通信状态

    a=0 for xgip in ${xgipset[*]} do let a+=1 fping $xgip|grep alive >/dev/null if [ $a != 3 ];then i ...

  2. Notepad++—设置背景颜色

    之前,编程一直用的都是黑色背景色,最近发现,黑色背景色+高光字体,时间久了对眼睛特别不好.感觉自己编程到现在几年时间,眼睛就很不舒服,甚至有青光眼的趋势.所以,改用白底黑字,即"日间模式&q ...

  3. hash_map,map,unordered_map效率

    利用unordered_map代替hash_map 实验环境 操作系统 fedora9 编译器版本 gcc4.3 实验方式 各种map使用插入和查找,比较速度和相关性能 代码 参考代码 下面测试说明了 ...

  4. UE4 C++工程以Game模式启动

    UE4版本:4.24.3源码编译版本 Windows10 + VS2019环境 UE4 C++工程,默认情况下VS中直接运行是启动Editor模式: 有时为了调试等目的需要以Game模式启动,可以避免 ...

  5. Mybatis批量添加、更新小结

    虽然是很基础的东西,不过难免会忘记,所以写个笔记巩固一下,顺便分享. 实体类: @Data public class EventOrder { ​ private Long id; ​ private ...

  6. 基于《CSAPP第九章 虚拟内存》的思考和总结

    在csapp的描述中,虚拟内存的形象更加具化,虚拟内存被组织为一个由存放在磁盘上的N个连续的字节大小的单元组成的数组,内存充当了磁盘的缓存,粗呢内存的许多概念与SRAM缓存是相似的.虚拟页面有以下三种 ...

  7. 巩固javawbe第二天

    巩固内容: <!DOCTYPE> 声明 <!DOCTYPE>声明有助于浏览器中正确显示网页. 网络上有很多不同的文件,如果能够正确声明HTML的版本,浏览器就能正确显示网页内容 ...

  8. C/C++ Qt 数据库与TableView多组件联动

    Qt 数据库组件与TableView组件实现联动,以下案例中实现了,当用户点击并选中TableView组件内的某一行时,我们通过该行中的name字段查询并将查询结果关联到ListView组件内,同时将 ...

  9. Linux学习 - 关机重启退出命令

    一.shutdown 1 功能 关机.重启操作 2 语法 shutdown  [-chr]  [时间选项] -h 关机 -r 重启 -c 取消前一个关机命令 二.halt.poweroff(关机) 三 ...

  10. 手写Mybatis和Spring整合简单版示例窥探Spring的强大扩展能力

    Spring 扩展点 **本人博客网站 **IT小神 www.itxiaoshen.com 官网地址****:https://spring.io/projects/spring-framework T ...