Suppose we have a string and we want to find the longest palindromic subtring which is also a prefix of the original string. Is there any way to solve this problem faster than the bruteforce technique?
# | User | Rating |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3831 |
3 | Radewoosh | 3646 |
4 | jqdai0815 | 3620 |
4 | Benq | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | gamegame | 3386 |
10 | ksun48 | 3373 |
# | User | Contrib. |
---|---|---|
1 | cry | 164 |
1 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
5 | -is-this-fft- | 158 |
6 | awoo | 157 |
7 | adamant | 156 |
8 | TheScrasse | 154 |
8 | nor | 154 |
10 | Dominater069 | 153 |
Suppose we have a string and we want to find the longest palindromic subtring which is also a prefix of the original string. Is there any way to solve this problem faster than the bruteforce technique?
Name |
---|
Manacher algorithm. Link to algorithm Implementation of solution
You can do it by prefix function of KMP algorithm.
The prefix function for this string is defined as an array π of length n, where π[i] is the length of the longest proper prefix of the substring s[0…i] which is also a suffix of this substring.
So when I appended the reverse of the string in the same string. So the prefix function value for the last index returns the longest proper prefix which is same as proper suffix (thereby a plaindrome because the string is reversed)
Do let me know if you have any further doubt! Please upvote if you find it useful and short algorithm.
thanks for the help.
Do upvote please!
did
Thanks!
You often can solve string problems without any smart functions (like zet or prefix): just use hashing!
If a substring is the answer then it is equal to a prefix. So, we can use this prefix as an answer (I hope that I understood the problem correctly).
Let's iterate over the length of the prefix. We can check whether this prefix is a palindrome or not using hashes of the given string and of the reverse string. The largest prefix is the answer.
Use hash, but hash might be hacked, despite that, Hashing requires at least $$$O(n\log n)$$$ pre-calc and during the query, we do something like ST table(I'm not sure if it is called that way) and can get the longest palindromic substring in $$$O(\log n)$$$, specifically, we pre-calc the hash value of $$$[l,l+2^i)$$$ by merging $$$[l,l+2^{i-1})$$$ and $$$[l+2^{i-1},l+2^{i-1}+2^{i-1})$$$
Use KMP, it can calculate the longest length of string that is both prefix and subfix of a substring(sorry for my poor English)
Hope to help you.
And also, the first hashing solution can also do the longest palindromic subtring (which don't have to be prefix)