美文网首页
[2018-12-09] [LeetCode-Week14] 6

[2018-12-09] [LeetCode-Week14] 6

作者: YuhiDiary | 来源:发表于2018-12-19 20:38 被阅读0次

https://leetcode.com/problems/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".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".


先判断长度为 1 和 2 的字符串的回文性。
对于长度在 3 以上的字符串,考虑
s[i] s[i+1] ..... s[i+len-2] s[i+len-1]
如果中间两端的字符 s[i] == s[i+len-1] , 那么当前字符串的回文性取决于中间的字符串。
最后把所有的字符串加起来即可。
循环时按照长度递增的顺序循环


class Solution {
public:
    int ans = 0;
    
    void procAns(int d) {
        ans += d;
    }
    
    int countSubstrings(string s) {
        int n = s.size();
        int d[1005][1005];
        
        for (int i = 0; i < n; i++) {
            procAns(d[i][1] = 1);
        }
        
        for (int i = 0; i < n; i++) {
            if (i + 1 >= n) break;
            procAns(d[i][2] = (s[i] == s[i+1]) ? 1 : 0);
            
        }
        
        for (int len = 3; len <= n; len++) {
            for (int i = 0; i < n; i++) {
                if (i + len -1 >= n) break;
                procAns(d[i][len] = (s[i] == s[i + len - 1]) ? d[i+1][len-2] : 0);
            }
        }
        
        return ans;
    }
};

相关文章

网友评论

      本文标题:[2018-12-09] [LeetCode-Week14] 6

      本文链接:https://www.haomeiwen.com/subject/kkvjkqtx.html