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
#[cfg(test)]
mod tests {
use super::Algorithm;
#[test]
fn test_gcd_of_strings() {
let result = Algorithm::gcd_of_strings(String::from("ABCABCABC"), String::from("ABC"));
assert_eq!(result.is_some(), true);
assert_eq!(result.unwrap(), "ABC");
let result1 = Algorithm::gcd_of_strings(String::from("HAHA"), String::from("ABC"));
assert_eq!(result1.is_none(), true);
}
#[test]
fn test_gcd() {
let result = Algorithm::gcd(8, 4);
assert_eq!(result, 4);
let result1 = Algorithm::gcd(8, 6);
assert_eq!(result1, 2);
}
}
pub struct Algorithm {}
impl Algorithm {
pub fn gcd_of_strings(str1: String, str2: String) -> Option<String> {
let str1_len = str1.len();
let str2_len = str2.len();
let gcd_result = Self::gcd(str1_len as i32, str2_len as i32);
let prefix_str: String = str1.chars().take(gcd_result as usize).collect();
if Self::gcd_of_strings_check(prefix_str.clone(), str1, gcd_result)
&& Self::gcd_of_strings_check(prefix_str.clone(), str2, gcd_result)
{
return Some(prefix_str);
}
return None;
}
fn gcd_of_strings_check(prefix_str: String, str1: String, gcd_result: i32) -> bool {
let mut temp_str: String = String::from("");
let mut result: bool = false;
for _ in 1..=str1.len() as i32 / gcd_result {
temp_str += &prefix_str;
if str1 == temp_str {
result = true;
break;
}
}
return result;
}
pub fn gcd(int1: i32, int2: i32) -> i32 {
if int1 % int2 == 0 {
return int2;
} else {
return Self::gcd(int2, int1 % int2);
}
}
}