您的位置:首页 > 其它

第十四周LeetCode

2017-12-06 23:04 120 查看
题目

Palindromic Substrings

难度 Medium

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.

实现思路

动态规划。假设dp[i][j]代表从第i个位置起到第j个位置的字符串是否为回文(即true还是false),那么dp[i][j]就取决于dp[i+1][j-1]的值以及s[i]是否等于s[j]。当i和j中间没有字符串时(此时i+1>j-1),若s[i]==s[j],那么d[i][j]仍然为true。

因此动态转移方程为 d[i][j]=(s[i]==s[j])&&(dp[i+1][j-1]||(i+1>j-1));

实现代码

int countSubstrings(string s) {
int n = s.size();
int count = 0;
vector<vector<int>> dp(n,vector<int>(n));
for (int j = 0; j < n; j++) {
dp[j][j] = 1;
count++;
for (int i = 0; i < j; i++) {
if (s[i]==s[j]&&(j-1<=i+1||dp[i+1][j-1])) {
dp[i][j]=1;
count++;
}
}
}
return count;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: