Efficient way to verify if a string is a rotated palindrome?

后端 未结 5 648
萌比男神i
萌比男神i 2021-01-12 03:49

A rotated palindrome is like \"1234321\", \"3432112\". The naive method will be cut the string into different pieces and concate them back and see if the string is a palindr

5条回答
  •  逝去的感伤
    2021-01-12 04:26

    Concatenate the string to itself, then do the classical palindrome research in the new string. If you find a palindrome whose length is longer or equal to the length of your original string, you know your string is a rotated palindrome.

    For your example, you would do your research in 34321123432112 , finding 21123432112, which is longer than your initial string, so it's a rotated palindrome.

    EDIT: as Richard Stefanec noted, my algorithm fails on 1121, he proposed that we change the >= test on the length by =.

    EDIT2: it should be noted than finding a palindrome of a given size isn't obviously easy. Read the discussion under Richard Stefanec post for more information.

提交回复
热议问题