686. Repeated String Match

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.

Notice: string "abc" repeated 0 times is "",  repeated 1 time is "abc" and repeated 2 times is "abcabc".

 

Example 1:

Input: a = "abcd", b = "cdabcdab"
Output: 3
Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.

Example 2:

Input: a = "a", b = "aa"
Output: 2

Example 3:

Input: a = "a", b = "a"
Output: 1

Example 4:

Input: a = "abc", b = "wxyz"
Output: -1

 

Constraints:

  • 1 <= a.length <= 104
  • 1 <= b.length <= 104
  • a and b consist of lower-case English letters.

Rust Solution

struct Solution;

impl Solution {
    fn repeated_string_match(a: String, b: String) -> i32 {
        let mut s = String::new();
        let n = a.len();
        let m = b.len();
        if n == 0 || m == 0 {
            return -1;
        }
        let mut k = m / n;
        if k * n < m {
            k += 1;
        }
        for _ in 0..k {
            s += &a;
        }
        if s.contains(&b) {
            return k as i32;
        }
        s += &a;
        if s.contains(&b) {
            return (k + 1) as i32;
        }
        -1
    }
}

#[test]
fn test() {
    let a = "abcd".to_string();
    let b = "cdabcdab".to_string();
    assert_eq!(Solution::repeated_string_match(a, b), 3);
}

Having problems with this solution? Click here to submit an issue on github.