Skip to content

Latest commit

 

History

History
42 lines (34 loc) · 960 Bytes

686.重复叠加字符串匹配.md

File metadata and controls

42 lines (34 loc) · 960 Bytes

686.重复叠加字符串匹配

/*
 * @lc app=leetcode.cn id=686 lang=typescript
 *
 * [686] 重复叠加字符串匹配
 */

// @lc code=start
function repeatedStringMatch(a: string, b: string): number {}
// @lc code=end

解法 1: 使用 API

function repeatedStringMatch(a: string, b: string): number {
  const [m, n] = [a.length, b.length]

  let cur = a.repeat(Math.floor(n / m)) + a.slice(0, n % m)

  for (let i = cur.length; i < (Math.floor(n / m) + 2) * m; i++) {
    if (cur === b) return Math.floor((i - 1) / m) + 1
    cur = cur.slice(1) + a[i % m]
  }
  return -1
}

Case

test.each([
  { input: { a: 'abcd', b: 'cdabcdab' }, output: 3 },
  { input: { a: 'a', b: 'aa' }, output: 2 },
  { input: { a: 'a', b: 'a' }, output: 1 },
  { input: { a: 'abc', b: 'wxyz' }, output: -1 },
])('input: a = $input.a, b = $input.b', ({ input: { a, b }, output }) => {
  expect(repeatedStringMatch(a, b)).toEqual(output)
})