Today, we will discover one of the basics algorithms to find the longest palindromic substring.
Given a string S, find the longest palindromic substring in S.
1. S = "abad", Result = "aba"
2. S = "codeedoc", Result = "codeedoc"
To come up with a solution we need to understand what the palindrome is. Basically, this is just a word which reads the same backward as forward (for more details see).
The main idea is to find all palindromes in S with even and odd lengths and keep track which one is the longest. To find odd length palindromes we fix center for every letter in S and expand it in both directions.
To find even length palindrome we fix center between two nearby letters in S and also expand it in both directions.
While expanding, if two opposite letters are equal then we add them to our potential palindrome.
That’s all for today. You can find the source code here, but I suggest you implement it by yourself.
Thank you for reading my blog and see you in a leaderboard :)
In this post, we will discover the basic algorithm to find the longest common substring of two strings.
Problem: Given two strings
Y, find the longest common substring.
1. X = "timetocode", Y = "timerightnow", Result = "time"
2. X = "abcabdef", Y = "abdf", Result = "abd"
Solution: Dynamic Programming
To solve this problem, we need to find all occurrences of all
X letters in
Y string. To keep intermediate results we can use a two-dimensional array of length
Even now we can see the result. But to make it more clear, let’s add some rules how to fill this table:
1. If X letter is not equal to Y letter then
Table[i][j] = 0.
2. If X letter is equal to Y letter then this is already common substring of length 1. If the previous letter was also substring then the length of a new substring is
Table[i][j] = Table[i - 1][j - 1] + 1 (prev length + current length).
Obviously, the length of the longest common substring is the maximum value in this table. And the actual substring can be reproduced by previous cells from the cell with maximum value to the cell with a value of one.
O(|X| * |Y|)
The source code for this problem you may find here. Thank you for reading my blog and have a nice coding!