Counting palindromic substrings in O(n)

后端 未结 3 1525
情书的邮戳
情书的邮戳 2020-12-07 15:01

Given a string (assume only English characters) S of length n, we can count the number of palindromic substrings with the following algorithm:

3条回答
  •  执笔经年
    2020-12-07 15:42

    For "normal" strings it should be rather efficient to look at each character as the potential "center" of a palindrome and then check if the surrounding characters actually build one:

    # check odd palindromes
    for center in range(len(ls)):
       # check how many characters to the left and right of |center|
       # build a palindrome
       maxoffs = min(center, len(ls)-center-1)
       offs = 0
       while offs <= maxoffs and ls[center-offs] == ls[center+offs]:
          offs += 1
       offs -= 1
       print ls[center-offs : center+offs+1]                                    
    
    # check for even palindromes
    for center in range(len(ls)-1):
       maxoffs = min(center, len(ls)-center-2)
       offs = 0
       while offs <= maxoffs and ls[center-offs] == ls[center+offs+1]:
          offs += 1
       offs -= 1
       if offs >= 0:
          print ls[center-offs : center+offs+2]
    

    For normal strings this should be about O(n), though in the worst case, for example if the string consists of only one character repeated over and over again, it will still take O(n2) time.

提交回复
热议问题