1143. 最长公共子序列
This commit is contained in:
+12
-17
@@ -1,29 +1,24 @@
|
||||
mod arr;
|
||||
struct Solution {}
|
||||
impl Solution {
|
||||
pub fn min_distance(word1: String, word2: String) -> i32 {
|
||||
let mut dp = vec![vec![0; word2.len() + 1]; word1.len() + 1];
|
||||
let word1 = word1.chars().collect::<Vec<char>>();
|
||||
let word2 = word2.chars().collect::<Vec<char>>();
|
||||
for i in 1..=word1.len() {
|
||||
dp[i][0] = dp[i - 1][0] + 1;
|
||||
}
|
||||
for i in 1..=word2.len() {
|
||||
dp[0][i] = dp[0][i - 1] + 1;
|
||||
}
|
||||
for i in 0..word1.len() {
|
||||
for j in 0..word2.len() {
|
||||
dp[i + 1][j + 1] = (dp[i][j] + if word1[i] != word2[j] { 1 } else { 0 })
|
||||
.min(dp[i][j + 1] + 1)
|
||||
.min(dp[i + 1][j] + 1);
|
||||
pub fn longest_common_subsequence(text1: String, text2: String) -> i32 {
|
||||
let mut dp = vec![vec![0; text2.len() + 1]; text1.len() + 1];
|
||||
let text1 = text1.chars().collect::<Vec<char>>();
|
||||
let text2 = text2.chars().collect::<Vec<char>>();
|
||||
for i in 0..text1.len() {
|
||||
for j in 0..text2.len() {
|
||||
dp[i + 1][j + 1] = dp[i + 1][j].max(dp[i][j + 1]);
|
||||
if text1[i] == text2[j] {
|
||||
dp[i + 1][j + 1] = dp[i + 1][j + 1].max(dp[i][j] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
dp[word1.len()][word2.len()]
|
||||
dp[text1.len()][text2.len()]
|
||||
}
|
||||
}
|
||||
fn main() {
|
||||
println!(
|
||||
"{:?}",
|
||||
Solution::min_distance("intention".to_string(), "execution".to_string())
|
||||
Solution::longest_common_subsequence("abcde".to_string(), "ace".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user