Complete the code to initialize the 2D vector for dynamic programming.
let mut dp = vec![vec![0; [1]]; s1.len() + 1];
We create a 2D vector with rows = s1 length + 1 and columns = s2 length + 1 to store substring lengths.
Complete the code to update dp when characters match.
if s1_bytes[i - 1] == s2_bytes[j - 1] { dp[i][j] = dp[i - 1][j - 1] [1] 1; }
When characters match, we add 1 to the diagonal dp value to extend the substring.
Fix the error in updating the maximum length found so far.
if dp[i][j] [1] max_len { max_len = dp[i][j]; end_index = i; }
We update max_len only if current dp[i][j] is greater than max_len.
Fill both blanks to extract the longest common substring from s1.
let result = &s1[[1]..[2]];
The substring starts at end_index - max_len and ends at end_index.
Fill all three blanks to complete the longest common substring function.
fn longest_common_substring(s1: &str, s2: &str) -> String {
let s1_bytes = s1.as_bytes();
let s2_bytes = s2.as_bytes();
let mut dp = vec![vec![0; [1]]; s1.len() + 1];
let mut max_len = 0;
let mut end_index = 0;
for i in 1..=s1.len() {
for j in 1..=s2.len() {
if s1_bytes[i - 1] == s2_bytes[j - 1] {
dp[i][j] = dp[i - 1][j - 1] [2] 1;
if dp[i][j] [3] max_len {
max_len = dp[i][j];
end_index = i;
}
}
}
}
s1[(end_index - max_len)..end_index].to_string()
}The dp table columns are s2 length + 1, we add 1 when characters match, and update max_len if current dp[i][j] is greater.
