leetcode647 - 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.
palindrome的条件:1.单个字母,2.两个一样的字母,3.如果len>2,s[i-1] == s[j+1]且是s[i, j]也是palindrome。
dp[i][j]表示s[i,j]是否为palindrome。loop之前先把对角线都set成1,只需要loop j从1~n-1, i从0到<j, 即grid的右上方部分,根据上面的条件check。
实现:
class Solution { public: int countSubstrings(string s) { int n = s.size(); vector<vector<int>> dp(n, vector<int>(n, 0)); int res = 0; for (int i=0; i<n; i++){ dp[i][i] = 1; res++; } for (int j=1; j<n; j++){ for (int i=0; i<j; i++){ if (j == i+1 && s[i] == s[j]){ dp[i][j] = 1; res++; } else if (j > i+1 && s[i] == s[j] && dp[i+1][j-1] == 1){ dp[i][j] = 1; res++; } } } return res; } };

浙公网安备 33010602011771号