Skip to content

Commit 593a4d0

Browse files
committed
686. Repeated String Match: AC
1 parent 347f1a1 commit 593a4d0

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,3 +497,4 @@ mod s0680_valid_palindrome_ii;
497497
mod s0682_baseball_game;
498498
mod s0684_redundant_connection;
499499
mod s0685_redundant_connection_ii;
500+
mod s0686_repeated_string_match;
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* [0686] Repeated String Match
3+
*
4+
* Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b​​​​​​ to be a substring of a after repeating it, return -1.
5+
* Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc".
6+
*
7+
* Example 1:
8+
*
9+
* Input: a = "abcd", b = "cdabcdab"
10+
* Output: 3
11+
* Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.
12+
*
13+
* Example 2:
14+
*
15+
* Input: a = "a", b = "aa"
16+
* Output: 2
17+
*
18+
*
19+
* Constraints:
20+
*
21+
* 1 <= a.length, b.length <= 10^4
22+
* a and b consist of lowercase English letters.
23+
*
24+
*/
25+
pub struct Solution {}
26+
27+
// problem: https://leetcode.com/problems/repeated-string-match/
28+
// discuss: https://leetcode.com/problems/repeated-string-match/discuss/?currentPage=1&orderBy=most_votes&query=
29+
30+
// submission codes start here
31+
32+
impl Solution {
33+
pub fn repeated_string_match(a: String, b: String) -> i32 {
34+
let mut c = String::new();
35+
for i in 0..(b.len() / a.len() + 3) {
36+
if c.contains(&b) {
37+
return i as i32;
38+
}
39+
c = format!("{}{}", c, a);
40+
}
41+
-1
42+
}
43+
}
44+
45+
// submission codes end
46+
47+
#[cfg(test)]
48+
mod tests {
49+
use super::*;
50+
51+
#[test]
52+
fn test_0686_example_1() {
53+
let a = "abcd".to_string();
54+
let b = "cdabcdab".to_string();
55+
let result = 3;
56+
57+
assert_eq!(Solution::repeated_string_match(a, b), result);
58+
}
59+
60+
#[test]
61+
fn test_0686_example_2() {
62+
let a = "a".to_string();
63+
let b = "aa".to_string();
64+
let result = 2;
65+
66+
assert_eq!(Solution::repeated_string_match(a, b), result);
67+
}
68+
}

0 commit comments

Comments
 (0)