forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
* Longest Palindromic Subsequence Algorithm is Added * test case added * Renamed
- Loading branch information
1 parent
5dde6a0
commit 779bc2f
Showing
3 changed files
with
37 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
def longest_palindromic_subsequence(str): | ||
n = len(str) | ||
|
||
# Create a table to store results of subproblems | ||
L = [[0 for x in range(n)] for x in range(n)] | ||
|
||
for i in range(n): | ||
L[i][i] = 1 | ||
|
||
|
||
for sub_string_length in range(2, n + 1): | ||
for i in range(n-sub_string_length + 1): | ||
j = i + sub_string_length-1 | ||
if str[i] == str[j] and sub_string_length == 2: | ||
L[i][j] = 2 | ||
elif str[i] == str[j]: | ||
L[i][j] = L[i + 1][j-1] + 2 | ||
else: | ||
L[i][j] = max(L[i][j-1], L[i + 1][j]); | ||
|
||
return L[0][n-1] | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters