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