【问题标题】:Deleting a Pattern from a String [closed]从字符串中删除模式 [关闭]
【发布时间】:2015-02-21 23:20:05
【问题描述】:

我不确定如何进行编码。因此,我有一个名为 S 的字符串和一个名为 M 的模式字符串。我想删除 S 中所有出现的 M。但是,当我删除 S 中出现的一次 M 时,我可能会创建另一个。例如,给定单词“aajjk”和模式“aj”。第一次删除后,它会变成“ajk”。在这个新字符串中,在第一次删除之后又出现了“aj”。所有删除后的最终字符串将是“k”。你能给我一些关于如何解决这个问题的提示吗,一些伪代码会很有帮助,因为我需要在实现中进行练习。

【问题讨论】:

  • 请不要破坏自己的问题;这使得人们花时间写的答案变得不那么有用了。

标签: regex string algorithm dynamic-programming


【解决方案1】:

如果你想要一个最坏情况的线性时间算法,那么一种方法是构造一个有限自动机,它接受以 M 结尾的字符串(例如,Knuth--Morris--Pratt),然后运行这个伪代码。

initialize a state stack to [initial state of the automaton]
initialize an empty character stack
for each character c in S:
    let q be the top of the state stack
    push delta(q, c) onto the state stack,
      where delta is the transition function of the automaton
    push c onto the character stack
    if the top of the state stack is an accepting state:
        pop length(M) values from both stacks
output the contents of the character stack

【讨论】:

  • 嗨,我有一些澄清。什么是转移函数,什么是自动机?
  • @PrashSom 有一整套关于字符串匹配算法的文献,我假设对它们有些熟悉。
【解决方案2】:

在 JS 中你可以这样做:

function delPattern(patt, str) {
    var res = str.replace(patt, "");
    if(patt.test(res) == true) {
        delPattern(patt, res);
    } else {
        console.log(res);
    }

}

var str = "aajjk"; 
delPattern(/aj/g, str);

"patt" 是模式。这里是“/aj/g”。 “g”代表全局,每个模式都匹配。使用“replace”功能,您可以用“”替换您的模式。之后,您询问该模式是否存在一次“if(patt.test(res) == true)”。如果是真的,那么再做同样的事情。否则,给我结果。

【讨论】:

    【解决方案3】:

    简单地说,只要执行替换会导致不同的字符串循环。伪代码:

    lastS = null
    while(lastS != S)
        lastS = S
        S.replace(M, '')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      相关资源
      最近更新 更多