题目描述

小栖最近很喜欢回文串,由于小栖的幸运数字是5,他想知道形似“abcba"的回文串在他给定的字符串中的数量

s.length <= 10^6

字符串s只包含小写字母

示例

  • 示例1 :

    输入:s = "abcba"
    输出:1
    
  • 示例2:

    输入:s = "abcbabcccb"
    输出:2
    解释:形似”abcba“的字符串有”abcba“和”cbabc“
    

    来源:九章算法


打卡水题, 很简单的字符串操作题. 根据题意可知5位数的字符串,以中间位分割,两侧对称位置相同,且单侧与中间位置的值均不同。从第二个位置(即第一个可能为回文字符串)开始遍历即可,秒过。

  • 题解:

    class Solution:
    """
    @param s: The given string
    @return: return the number of Five-character palindrome
    """
    
    def Fivecharacterpalindrome(self, s):
        # write your code here
        result = 0
        s_len = len(s)
        for x in range(2, s_len-2):
            if s[x+1] == s[x-1] and s[x+2] == s[x-2] and s[x] != s[x+1] and  s[x] != s[x+2] and s[x+1] != s[x+2]:
                result = result+1
        return result