算法博客3 - 回文串问题

算法博客3 - 回文串问题

题目描述:

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.

解题思路:

对字符串进行两层遍历,第一层确定当前中心字符,第二层从中心字符往左右两边遍历并比较字符是否相等。若回文串字符数为偶数,则选取两个字符作为中心字符。

代码:

	class Solution {
	public:
	    int countSubstrings(string s) {
	        int result = 0, n = s.length();
	        for(int i = 0; i < n; i++){
	            for(int j = 1; i-j >= 0 && i+j < n && s[i-j] == s[i+j]; j++)result++;
	            for(int j = 0; i-1-j >= 0 && i+j < n && s[i-1-j] == s[i+j]; j++)result++; 
	        }
	        return result;
	    }
	};

你可能感兴趣的:(算法博客)