【问题标题】:Find all the occurences of a string as a subsequence in a given string在给定字符串中查找所有出现的字符串作为子序列
【发布时间】:2020-01-23 22:31:12
【问题描述】:

给定字符串 A 和 B,找出所有在 A 中出现的 B 作为子序列。

例子:

A = "mañana de la mañana"

B = "manana"

答案:

0 -> ma​​ñana de la mañana

1 -> ma​​ñana de la mañana

2 -> ma​​ñana de la mañana

...

根据我发现的算法here 计算出现次数,其中有 16 次。我需要一种算法来找到所有这些子序列并报告它们的索引。

【问题讨论】:

  • 你自己尝试了什么?
  • 主要是考虑如何修改我在该链接中找到的算法以获得答案。
  • 你能举例说明你希望如何返回数据吗?
  • 您想要返回的子序列的“索引”是什么意思?
  • [ [0,1,2,3,4,5], [0,1,2,3,4,11], [0,1,2,16,17,18] , ... ]

标签: algorithm dynamic-programming


【解决方案1】:

基本的递归是这样的

/** 
 * @param  {[type]} iA current letter index in A
 * @param  {[type]} iB current letter index in B
 */ 
function rec (A, B, iA, iB, indices, solutions) {
  if (iB === B.length) {
    // copy the array if solution
    solutions.push(indices.slice(0))
    return
  }
  if (iA === A.length) {
    return
  }
  const cb = B[iB]
  // find all occurrences of cb in A
  for (let i = iA; i < A.length; ++i) {
    const ca = A[i]
    if (ca === cb) {
      indices[iB] = i
      //match the next char
      rec(A, B, i + 1, iB + 1, indices, solutions)
    }
  }
}
const A = "mañana de la mañana"
const B = "mañana"
const solutions = []
rec(A, B, 0, 0, [], solutions)
console.log(solutions.map(x => [
  x.join(','), A.split('').map((c, i) => x.includes(i) ? c.toUpperCase() : c).join('')
]))

对于动态方法

  • 构建所有以m 结尾的序列并将它们存储到S_m
  • S_m构建所有以a结尾的序列并将它们存储到S_{ma}
  • 等等

const A = "mañana de la mañana"
const B = "mañana"
let S = A.split('').flatMap((a, i) => a === B[0] ? [[i]] : [])
// S is initially [ [0], [13] ]
B.split('').slice(1).forEach(b => {
  const S_m = []
  S.forEach(s => {
    const iA = s[s.length - 1]
    // get the last index from current sequence
    // and look for next char in A starting from that index
    for (let i = iA + 1; i < A.length; ++i) {
      const ca = A[i]
      if (ca === b) {
        S_m.push(s.concat(i))
      }
    }
  })
  S = S_m
})
console.log(S.map(x => [
  x.join(','), A.split('').map((c, i) => x.includes(i) ? c.toUpperCase() : c).join('')
]))

【讨论】:

  • 看起来这行得通。只是想了解逻辑和时间复杂度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 2013-03-22
  • 2015-12-23
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多