美文网首页
647. Palindromic Substrings 笔记

647. Palindromic Substrings 笔记

作者: 赵智雄 | 来源:发表于2017-12-05 15:44 被阅读15次

    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".
    

    写个判断回文字符串的函数,计数。简单粗暴。

    class Solution {
    public:
        int countSubstrings(string s) {
            vector<char>str(s.size(), '0');
            for (int i = 0; s[i] != '\0'; i++)
            {
                str[i] = s[i];
            }
            int res = 0;
            for (int j = 0; j < str.size(); j++)
            {
                for (int k = j; k < str.size(); k++)
                {
                    if (isPalindromic(str, j, k))
                        res++;
                }
            }
            return res;
        }
        bool isPalindromic(vector<char> &str, int start, int end)
        {
            while (start < end)
            {
                if (str[start] != str[end])
                {
                    return false;
                }
                start++;
                end--;
            }
            return true;
        }
    };
    

    相关文章

      网友评论

          本文标题:647. Palindromic Substrings 笔记

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