647. Palindromic Substrings
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".
给定一个字符串,统计所有的回文字符串。
解决方案:回文有两种形式:aba或abba。分别选定一个中心,向左右扩张,如果增加的左右两个字符相等,统计+1,接着扩张。
class Solution { public: int countSubstrings(string s) { int res = 0; // aba for( int i=0; i<s.length(); ++i ){ int j = 0; while( i-j>=0 && i+j<s.length() && s[i-j]==s[i+j] ){ res++; j++; } } // abba for( int i=0; i<s.length()-1; ++i){ int j = 0; while( i-j>=0 && i+j+1<s.length() && s[i-j]==s[i+j+1] ){ res++; j++; } } return res; } };
当然,统计回文还有一种常用的动态规划的方法。见:5. Longest Palindromic Substring