算法第11周Palindromic Substrings[medium]
2017-11-18 00:27
134 查看
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:
The input string length won’t exceed 1000.
Analysis
本题是返回给定字符串中的回文子串个数。回文字符串就是从左到右和从右到左都相同的字符串。
我们可以利用动态规划求最长回文子串的方法得到字符串中的回文子串个数。
首先来回忆得到最长回文子串的动态规划。
我们首先声明一个二维的布尔数组,大小为n*n ,p
p[i][j]表示子串s[i,j]是否为回文串。
if i >= j p(i,j) = true; if s[i] = s[j] p[i][j] = p[i+1][j-1] otherwise p[i][j] = false
在计算过程中要注意p[i][j]的计算顺序,即i,j是如何变化的。
我们是从(i,i)出发依次计算(i,i+1)(i,i+2)…在每一次计算过程中遍历完所有的i;
Solution
class Solution { public: int countSubstrings(string s) { int n = s.length(); bool p ; int res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i >= j) { p[i][j] = true; } else { p[i][j] = false; } } } for (int i = 1; i < n; i++) { for (int j = 0; j < n-i; j++) { if (s[j] == s[j+i]) { p[j][j+i] = p[j+1][j+i-1]; } else { p[j][j+i] = false; } if (p[j][j+i] == true) res++; } } return res+n; } };
Discussion
还有一种做法就是对于字符串中的字符,以她为中心向外扩展,判断其是否为回文串。int countSubstrings(string s) { int res = 0, n = s.length(); for(int i = 0; i < n; i++){ for(int j = 0; i-j >= 0 && i+j < n && s[i-j] == s[i+j];j++)res++; //substring s[i-j, ..., i+j] for(int j = 0; i-1-j >= 0 && i+j < n && s[i-1-j] == s[i+j]; j++)res++; //substring s[i-1-j, ..., i+j] } return res; }
相关文章推荐
- 算法第七周Delete Node in a BST[medium]
- 第11周项目1-验证算法(2)二叉树构造算法的验证
- 第11周项目1 验证算法(2)二叉树构造算法的验证
- 第11周项目1-(3)中序线索化二叉树的算法验证
- 算法第八周Number of Longest Increasing Subsequence[medium]
- 第11周项目1-验证算法(2)二叉树构造算法的验证
- (算法分析Week11)Swap Nodes in Pairs[Medium]
- 算法分析与设计丨第四周丨LeetCode(7)——Find Bottom Left Tree Value(Medium)
- 【第11周 项目1 - 二叉树算法验证(3)中序线索化二叉树的算法验证】
- 算法设计与分析(8)-- Container With Most Water(难度:Medium)
- 第11周项目1-验证算法(4)哈夫曼编码的算法验证
- 第11周项目1 验证算法(4)哈夫曼编码的算法验证
- (算法分析Week7)Divide Two Integers[Medium]
- 第11周 项目1(中序线索化二叉树的算法验证)
- 第11周项目1- 图基本算法库
- 第11周项目1-验证算法(1)层次遍历算法的验证
- (算法分析Week10)ZigZag Conversion[Medium]
- 第11周、项目1.2—验证算法
- 第11周 项目1-验证算法(3)线索化二叉树(中序)
- 算法第三周 3Sum[medium]