返回介绍

solution / 0600-0699 / 0686.Repeated String Match / README_EN

发布于 2024-06-17 01:03:35 字数 3443 浏览 0 评论 0 收藏 0

686. Repeated String Match

中文文档

Description

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

 

Constraints:

  • 1 <= a.length, b.length <= 104
  • a and b consist of lowercase English letters.

Solutions

Solution 1

class Solution:
  def repeatedStringMatch(self, a: str, b: str) -> int:
    m, n = len(a), len(b)
    ans = ceil(n / m)
    t = [a] * ans
    for _ in range(3):
      if b in ''.join(t):
        return ans
      ans += 1
      t.append(a)
    return -1
class Solution {
  public int repeatedStringMatch(String a, String b) {
    int m = a.length(), n = b.length();
    int ans = (n + m - 1) / m;
    StringBuilder t = new StringBuilder(a.repeat(ans));
    for (int i = 0; i < 3; ++i) {
      if (t.toString().contains(b)) {
        return ans;
      }
      ++ans;
      t.append(a);
    }
    return -1;
  }
}
class Solution {
public:
  int repeatedStringMatch(string a, string b) {
    int m = a.size(), n = b.size();
    int ans = (n + m - 1) / m;
    string t = "";
    for (int i = 0; i < ans; ++i) t += a;
    for (int i = 0; i < 3; ++i) {
      if (t.find(b) != -1) return ans;
      ++ans;
      t += a;
    }
    return -1;
  }
};
func repeatedStringMatch(a string, b string) int {
  m, n := len(a), len(b)
  ans := (n + m - 1) / m
  t := strings.Repeat(a, ans)
  for i := 0; i < 3; i++ {
    if strings.Contains(t, b) {
      return ans
    }
    ans++
    t += a
  }
  return -1
}
function repeatedStringMatch(a: string, b: string): number {
  const m: number = a.length,
    n: number = b.length;
  let ans: number = Math.ceil(n / m);
  let t: string = a.repeat(ans);

  for (let i = 0; i < 3; i++) {
    if (t.includes(b)) {
      return ans;
    }
    ans++;
    t += a;
  }

  return -1;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文