|
| 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