647. Palindromic Substrings

Description

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.

Solution 

Approach #1: DP New Charactor + Previous Str 

 

class Solution {
public:
	int countSubstrings(string s) {
		return helper(s, s.size() - 1);
	}

	int helper(string s, int end) {

		if (-1 == end) return 0;

		int count = 0;
		for (int i = 0; i <= end; i++)
			if (isP(s, i, end)) count++;

		return helper(s, end - 1) + count;
	}

	bool isP(string &s, int start, int end) {
		while (start <= end)
			if (s[start++] != s[end--]) return false;

		return true;
	}
};
class Solution {
public:
	int countSubstrings(string s) {
		if (0 == s.size()) return 0;
		int count = 0;
		for (int j = 0; j < s.size(); j++)
			for (int i = 0; i <= j; i++)
				if (isP(s, i, j)) count++;

		return count;
	}

	bool isP(string &s, int start, int end) {
		while (start <= end) 
			if (s[start++] != s[end--]) return false;
		
		return true;
	}
};

Approach #2: Expand Around Center

class Solution {
public:
    int countSubstrings(string s) {
        int axisNum = 2 * s.size() - 1;
        int left = 0, right = 0, ans = 0;
        
        for(int i = 0; i < axisNum; i++) {
            left = i/2;
            right = left + i%2;
            while (left>=0 && right<s.size() && s[left--] == s[right++])  ans++;
        }
        
        return ans;
    }
};

Approach #3: Manacher's Algorithm 馬拉車

class Solution {
public:
    int countSubstrings(string s) {
        
        int ret = 0;
        
        vector<char> str(2*s.size() + 3, 0);
        vector<int> redius(2*s.size() + 3, 0);
        
        int center = 0, right = 0;
        
        str[0] = '@';
        str[1] = '#';
        int j = 2;
        for (int i=0; i<s.size(); i++){
           str[j++] = s[i];
           str[j++] = '#'; 
        } 
        str[j++] = '$';    
        
        for(int i=2; i<str.size()-2; i++){
            
            //reduce repeated calculate by using previous result;
            if (i<right)  redius[i] = min(right -i, redius[2*center - i]);
            
            //calculate outside of right boundary            
            while (str[i + redius[i] + 1] == str[i - redius[i] - 1]) redius[i]++;
            
            if (i + redius[i] > right) {
                right = i + redius[i];
                center = i;
            }
            
        }
       
        // +1 means the charactor itself;
        for (int e: redius) ret += (e+1)/2;
        
        return ret;
    }
};

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章