|
| 1 | +// Longest common substring via Dynamic Programming |
| 2 | +// longest_common_substring(a, b) returns the length of longest common substring between the strings a and b. |
| 3 | +pub fn longest_common_substring(text1: String, text2: String) -> i32 { |
| 4 | + let m = text1.len(); |
| 5 | + let n = text2.len(); |
| 6 | + |
| 7 | + let t1 = text1.as_bytes(); |
| 8 | + let t2 = text2.as_bytes(); |
| 9 | + |
| 10 | + // BottomUp Tabulation |
| 11 | + let mut dp = vec![vec![0; n + 1]; m + 1]; |
| 12 | + let mut ans = 0; |
| 13 | + for i in 1..=m { |
| 14 | + for j in 1..=n { |
| 15 | + if i == 0 || j == 0 { |
| 16 | + dp[i][j] = 0; |
| 17 | + continue; |
| 18 | + } |
| 19 | + if t1[i - 1] == t2[j - 1] { |
| 20 | + dp[i][j] = 1 + dp[i - 1][j - 1]; |
| 21 | + ans = std::cmp::max(ans, dp[i][j]); |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + ans |
| 27 | +} |
| 28 | + |
| 29 | +#[cfg(test)] |
| 30 | +mod tests { |
| 31 | + use super::*; |
| 32 | + |
| 33 | + #[test] |
| 34 | + fn test1() { |
| 35 | + assert_eq!( |
| 36 | + longest_common_substring(String::from(""), String::from("")), |
| 37 | + 0 |
| 38 | + ); |
| 39 | + } |
| 40 | + #[test] |
| 41 | + fn test2() { |
| 42 | + assert_eq!( |
| 43 | + longest_common_substring(String::from("a"), String::from("")), |
| 44 | + 0 |
| 45 | + ); |
| 46 | + } |
| 47 | + #[test] |
| 48 | + fn test3() { |
| 49 | + assert_eq!( |
| 50 | + longest_common_substring(String::from(""), String::from("a")), |
| 51 | + 0 |
| 52 | + ); |
| 53 | + } |
| 54 | + #[test] |
| 55 | + fn test4() { |
| 56 | + assert_eq!( |
| 57 | + longest_common_substring(String::from("a"), String::from("a")), |
| 58 | + 1 |
| 59 | + ); |
| 60 | + } |
| 61 | + #[test] |
| 62 | + fn test5() { |
| 63 | + assert_eq!( |
| 64 | + longest_common_substring(String::from("abcdef"), String::from("bcd")), |
| 65 | + 3 |
| 66 | + ); |
| 67 | + } |
| 68 | + #[test] |
| 69 | + fn test6() { |
| 70 | + assert_eq!( |
| 71 | + longest_common_substring(String::from("abcdef"), String::from("xabded")), |
| 72 | + 2 |
| 73 | + ); |
| 74 | + } |
| 75 | + #[test] |
| 76 | + fn test7() { |
| 77 | + assert_eq!( |
| 78 | + longest_common_substring(String::from("GeeksforGeeks"), String::from("GeeksQuiz")), |
| 79 | + 5 |
| 80 | + ); |
| 81 | + } |
| 82 | + #[test] |
| 83 | + fn test8() { |
| 84 | + assert_eq!( |
| 85 | + longest_common_substring(String::from("abcdxyz"), String::from("xyzabcd")), |
| 86 | + 4 |
| 87 | + ); |
| 88 | + } |
| 89 | + #[test] |
| 90 | + fn test9() { |
| 91 | + assert_eq!( |
| 92 | + longest_common_substring(String::from("zxabcdezy"), String::from("yzabcdezx")), |
| 93 | + 6 |
| 94 | + ); |
| 95 | + } |
| 96 | + #[test] |
| 97 | + fn test10() { |
| 98 | + assert_eq!( |
| 99 | + longest_common_substring( |
| 100 | + String::from("OldSite:GeeksforGeeks.org"), |
| 101 | + String::from("NewSite:GeeksQuiz.com") |
| 102 | + ), |
| 103 | + 10 |
| 104 | + ); |
| 105 | + } |
| 106 | +} |
0 commit comments