LeetCode#647 Palindromic Substrings题解(C++版)

来源:互联网 发布:淘宝保暖卫衣长款 编辑:程序博客网 时间:2024/06/02 07:11

题干

这里写图片描述

原题网址:
https://leetcode.com/problems/palindromic-substrings/description/

题干解析

给你一个字符串,找出它的所有回文子串,输出回文子串的总数。

解题思路

这道题还是比较简单的,从不同长度的子串(从1-s.size()),遍历所有的可能的子串情况,并判断其是否为回文子串,是的话,count++。最后返回count。

代码

class Solution {public:    int countSubstrings(string s) {        int count = 0;        for (int i = 1; i <= s.size(); i++) {            for (int j = 0; j <= s.size() - i; j++) {                string temp = s.substr(j, i);                string re_temp = temp;                reverse(re_temp.begin(), re_temp.end());                if (temp == re_temp) {                    count++;                }            }        }        return count;    }};