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 | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
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)