647. Palindromic Substrings

Problem:

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.

思路

Solution (C++):

int countSubstrings(string s) {
    int m = s.length(), count = 0;
    for (int i = 0; i < m; ++i) {
        for (int j = 1; j <= m-i; ++j) {
            if (isPalindrome(s.substr(i, j))) count++;
        }
    }
    return count;
}

bool isPalindrome(string str) {
    int n = str.length();
    if (n == 1) return true;
    for (int i = 0; i <= (n-1)/2; ++i) {
        if (str[i] != str[n-1-i]) return false;
    }
    return true;
}

性能

Runtime: 992 ms  Memory Usage: 456.1 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12599483.html