The Longest Common Subsequence (LCS) problem is a classic dynamic programming problem. Given two sequences, the LCS is the longest sequence that appears in both of them in the same relative order, but not necessarily contiguous.
Here's a Rust implementation that calculates the length of the LCS and then reconstructs the subsequence itself.
use std::cmp::max;
/// Calculates the Longest Common Subsequence (LCS) of two strings.
///
/// This implementation uses dynamic programming to first build a table
/// representing the lengths of common subsequences for all prefixes,
/// and then backtracks through the table to reconstruct the actual LCS string.
///
/// # Arguments
/// * `s1` - The first input string.
/// * `s2` - The second input string.
///
/// # Returns
/// A `String` containing the Longest Common Subsequence.
///
/// # Examples
/// ```
/// assert_eq!(longest_common_subsequence("ABCBDAB", "BDCABA"), "BCBA");
/// assert_eq!(longest_common_subsequence("AGGTAB", "GXTXAYB"), "GTAB");
/// assert_eq!(longest_common_subsequence("HARRY", "SALLY"), "AY");
/// assert_eq!(longest_common_subsequence("ABCD", "AEBD"), "ABD");
/// assert_eq!(longest_common_subsequence("ABCD", "EFGH"), "");
/// assert_eq!(longest_common_subsequence("", "ANYTHING"), "");
/// ```
pub fn longest_common_subsequence(s1: &str, s2: &str) -> String {
let chars1: Vec<char> = s1.chars().collect();
let chars2: Vec<char> = s2.chars().collect();
let m = chars1.len();
let n = chars2.len();
// Create a 2D DP table (m+1 rows, n+1 columns) initialized with zeros.
// dp[i][j] will store the length of the LCS of chars1[0...i-1] and chars2[0...j-1].
let mut dp: Vec<Vec<usize>> = vec![vec![0; n + 1]; m + 1];
// Fill the DP table
for i in 1..=m {
for j in 1..=n {
// If characters match, add 1 to the diagonal value
if chars1[i - 1] == chars2[j - 1] {
dp[i][j] = 1 + dp[i - 1][j - 1];
} else {
// If characters don't match, take the maximum of
// the value from the cell above (excluding chars1[i-1])
// and the value from the cell to the left (excluding chars2[j-1])
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
// Reconstruct the LCS string by backtracking through the DP table
let mut lcs_chars: Vec<char> = Vec::new();
let mut i = m;
let mut j = n;
while i > 0 && j > 0 {
// If current characters match, it's part of the LCS
if chars1[i - 1] == chars2[j - 1] {
lcs_chars.push(chars1[i - 1]);
i -= 1;
j -= 1;
} else if dp[i - 1][j] > dp[i][j - 1] {
// If the value came from the top cell, move up
i -= 1;
} else {
// If the value came from the left cell (or both were equal), move left
j -= 1;
}
}
// The characters were collected in reverse order, so reverse them and collect into a String
lcs_chars.into_iter().rev().collect()
}
fn main() {
// Test cases
println!("LCS(\"ABCBDAB\", \"BDCABA\") = \"{}\"", longest_common_subsequence("ABCBDAB", "BDCABA")); // Expected: BCBA
println!("LCS(\"AGGTAB\", \"GXTXAYB\") = \"{}\"", longest_common_subsequence("AGGTAB", "GXTXAYB")); // Expected: GTAB
println!("LCS(\"HARRY\", \"SALLY\") = \"{}\"", longest_common_subsequence("HARRY", "SALLY")); // Expected: AY
println!("LCS(\"ABCD\", \"AEBD\") = \"{}\"", longest_common_subsequence("ABCD", "AEBD")); // Expected: ABD
println!("LCS(\"ABCD\", \"EFGH\") = \"{}\"", longest_common_subsequence("ABCD", "EFGH")); // Expected: ""
println!("LCS(\"\", \"ANYTHING\") = \"{}\"", longest_common_subsequence("", "ANYTHING")); // Expected: ""
println!("LCS(\"RUST\", \"GO\") = \"{}\"", longest_common_subsequence("RUST", "GO")); // Expected: ""
println!("LCS(\"RUST\", \"TRUST\") = \"{}\"", longest_common_subsequence("RUST", "TRUST")); // Expected: RST
println!("LCS(\"ABC\", \"ABC\") = \"{}\"", longest_common_subsequence("ABC", "ABC")); // Expected: ABC
}
Explanation:
-
longest_common_subsequence(s1: &str, s2: &str) -> String:
- Takes two string slices (
&str) as input.
- Returns a
String which is the reconstructed LCS.
-
Convert to Vec<char>:
let chars1: Vec<char> = s1.chars().collect();
let chars2: Vec<char> = s2.chars().collect();
- This converts the input string slices into vectors of characters. This is done for easier indexing (
chars1[i-1]) as string slicing in Rust can be more complex for char access due to UTF-8 encoding.
-
Dynamic Programming Table Initialization (dp):
let m = chars1.len();
let n = chars2.len();
let mut dp: Vec<Vec<usize>> = vec![vec![0; n + 1]; m + 1];
- A 2D vector
dp is created with dimensions (m+1) x (n+1). The extra row and column are for the base cases (representing an empty prefix of one of the strings).
dp[i][j] will store the length of the LCS of the prefix chars1[0...i-1] and chars2[0...j-1].
-
Filling the DP Table:
- The nested
for loops iterate from 1 to m (inclusive) and 1 to n (inclusive).
if chars1[i - 1] == chars2[j - 1]: If the characters at the current position (remembering i-1 and j-1 for 0-based indexing of chars1/chars2) are equal, it means they contribute to the LCS. The length is 1 plus the LCS length of the previous subproblems (dp[i-1][j-1]).
else: If the characters do not match, the LCS length for dp[i][j] is the maximum of:
dp[i - 1][j]: LCS length without chars1[i-1].
dp[i][j - 1]: LCS length without chars2[j-1].
- We use
std::cmp::max for this.
-
Reconstructing the LCS String:
This implementation is efficient with a time complexity of O(mn) and space complexity of O(mn), where 'm' and 'n' are the lengths of the two strings.