Skip to content

Commit

Permalink
64: Re-submit
Browse files Browse the repository at this point in the history
  • Loading branch information
sankichi92 committed Dec 30, 2023
1 parent 98d68e7 commit 3c144ae
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions 64-longest-common-subsequence/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
use std::collections::HashMap;

pub fn longest_common_subsequence(text1: String, text2: String) -> i32 {
let (longer, shorter) = if text1.len() >= text2.len() {
(text1, text2)
} else {
(text2, text1)
};

let mut char_to_indices = HashMap::new();
for (i, char) in shorter.chars().enumerate() {
let entry = char_to_indices.entry(char).or_insert(vec![]);
entry.push(i)
}

let mut lengths = vec![0; shorter.len()];
// println!("{:?}", shorter.chars().collect::<Vec<char>>());

for current in longer.chars() {
for (i, char) in shorter.chars().enumerate() {
if current == char {
if let Some(indices) = char_to_indices.get(&current) {
for &i in indices.iter().rev() {
lengths[i] = lengths.iter().take(i).max().unwrap_or(&0) + 1;
break;
}
}
// println!("{}: {:?}", current, lengths)
}

*lengths.iter().max().unwrap()
Expand Down Expand Up @@ -56,4 +61,12 @@ mod tests {
5
)
}

#[test]
fn failed_case2() {
assert_eq!(
longest_common_subsequence("abcba".to_string(), "abcbcba".to_string()),
5
)
}
}

0 comments on commit 3c144ae

Please sign in to comment.