您的位置:首页 > 其它

算法第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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: