1. 程式人生 > >LeetCode647. Palindromic Substrings

LeetCode647. Palindromic Substrings

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

Example 2:

Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Note:

  1. The input string length won't exceed 1000.

題目:判斷給定的字串中迴文子串的個數.

迴文有兩種模式,aba或者abba.因此分別對迴文中心為奇數和偶數進行判斷,如果迴文中心兩側的字元相等,那麼該子串為迴文.

第一種方式是先固定迴文中心,然後不斷的向兩側外擴,判斷兩側的值是否相等.如果相等,為迴文.如果不相等,更新迴文中心.

#include<iostream>
using namespace std;


class Solution {
public:
    int countSubstrings(string s) {
        for(size_t i=0; i<s.size();i++){
            //分別考慮迴文中心為奇數和偶數的情況
            expand(s, i, i);
            expand(s, i, i+1);
        }
        return count;
    }

private:
    int count=0;

    void expand(const string &s, int start, int end){
        while(start >= 0 && end < s.length() && s[start] == s[end]){
            start--;
            end++;
            count++;
        }
    }
};

int main(int argc, char const *argv[])
{
    Solution sln;
    cout << sln.countSubstrings("abccba") << endl;
    return 0;
}

還有一種方法是先固定一種迴文長度,然後對字串中的每個位置擷取該長度的子串進行判斷.如果第i個字元到第j個字元所組成的子串為迴文,那麼dp[i][j]=true,否則為false.那麼我們就可以根據dp[i][j]的值以及s[i-1]和s[j+1]是否相等來更新dp[i-1][j+1].

#include<iostream>
#include<vector>
using namespace std;


class Solution {
public:
    int countSubstrings(string s) {
        if(s.length() == 0)
            return 0;
        
        vector<vector<bool>> dp(s.length(), vector<bool>(s.length(), false));

        int count = 0;
        for(int i=0; i< s.length(); i++){
            
            dp[i][i] = true;
            count++;
            if(i+1 < s.length() && s[i] == s[i+1]){
                dp[i][i+1] = true;
                //cout << i<<"," << i+1 << endl;
                count++;
            }
        }

        //擷取substrlen長度的字串,判斷兩側的字元是否相等
        for(int substrlen = 1; substrlen<=s.length(); substrlen++){
            for(int i = 1; i< s.length()-substrlen; i++){
                int j = i+substrlen-1;
                if(dp[i][j] && s[i-1] == s[j+1]){
                    dp[i-1][j+1] = true;
                    //cout << i-1 <<"," << j+1 << endl;
                    count++;
                }
            }
        }
        return count;
    }
};


int main(int argc, char const *argv[])
{
    Solution sln;
    cout << sln.countSubstrings("abccba") << endl;
    return 0;
}