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

后端 未结 5 645
萌比男神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:44

    I would like to propose one simple solution, using only conventional algorithms. It will not solve any harder problem, but it should be sufficient for your task. It is somewhat similar to the other two proposed solutions, but none of them seems to be concise enough for me to read carefully.

    First step: concatenate the string to itself (abvc - > abvcabvc) as in all other proposed solutions.

    Second step: do Rabin-Karp precalculation (which uses rolling hash) on the newly obtained string and its reversed.

    Third step: Let the string be with length n. For each index iin 0...n-1 check if the substring of the doubled string [i, i + n - 1] is palindrome in constant time, using the Rabin-Karp precalculations (basically the obtained value in for the substring in the forward and the reversed direction should be equal).

    Conclusion: if third step found any palindrome - then the string is rotated palindrome. If not - then it is not.

    PS: Rabin Karp uses hashes, and collisions are possible even for non-coinciding strings. Thus it is a good idea to make verifying brute force check for equality if such is induced by the hash checks. Still if the hash functions used in the Rabin Karp are good, the amortized speed of the solution should remain O(n).

提交回复
热议问题