Skip to content

Commit 8c18f07

Browse files
authored
feat: Add Longest Palindromic Subsequence algorithm in R (#164)
1 parent 9e23362 commit 8c18f07

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Longest Palindromic Subsequence in R
2+
# Author: sgindeed
3+
# Description: Finds and prints the longest palindromic subsequence and its length
4+
5+
# Ask for user input
6+
input.string <- readline(prompt = "Enter a string: ")
7+
8+
# Convert string to lowercase for consistency
9+
clean.string <- tolower(input.string)
10+
11+
# Get length of string
12+
n <- nchar(clean.string)
13+
14+
# Split string into characters
15+
chars <- strsplit(clean.string, "")[[1]]
16+
17+
# Initialize DP table for lengths
18+
dp <- matrix(0, nrow = n, ncol = n)
19+
20+
# Each single character is a palindrome of length 1
21+
for (i in seq_len(n)) {
22+
dp[i, i] <- 1
23+
}
24+
25+
# Fill the DP table
26+
for (cl in 2:n) {
27+
for (i in 1:(n - cl + 1)) {
28+
j <- i + cl - 1
29+
if (chars[i] == chars[j] && cl == 2) {
30+
dp[i, j] <- 2
31+
} else if (chars[i] == chars[j]) {
32+
dp[i, j] <- dp[i + 1, j - 1] + 2
33+
} else {
34+
dp[i, j] <- max(dp[i + 1, j], dp[i, j - 1])
35+
}
36+
}
37+
}
38+
39+
# Function to reconstruct the subsequence
40+
reconstructLPS <- function(chars, dp, i, j) {
41+
if (i > j) {
42+
return("")
43+
}
44+
if (i == j) {
45+
return(chars[i])
46+
}
47+
if (chars[i] == chars[j]) {
48+
return(paste0(chars[i], reconstructLPS(chars, dp, i + 1, j - 1), chars[j]))
49+
}
50+
if (dp[i + 1, j] > dp[i, j - 1]) {
51+
return(reconstructLPS(chars, dp, i + 1, j))
52+
} else {
53+
return(reconstructLPS(chars, dp, i, j - 1))
54+
}
55+
}
56+
57+
# Get the longest palindromic subsequence
58+
lps <- reconstructLPS(chars, dp, 1, n)
59+
60+
# Display the result
61+
cat("Longest Palindromic Subsequence:", lps, "\n")
62+
cat("Length:", nchar(lps), "\n")

0 commit comments

Comments
 (0)