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?
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 156 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | nor | 152 |
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?
Название |
---|
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)