【问题标题】:Algorithm - String matching based on repetition factors算法 - 基于重复因子的字符串匹配
【发布时间】:2014-05-12 16:36:58
【问题描述】:

我有三个字符串作为输入 (A,B,C)。

A = "SLOVO",B = "单词",C =

我需要找到算法来决定,如果字符串 C 是无限重复字符串 A 和 B 的串联。重复示例:A^2 = "SLOVOSLOVO" 并且在字符串 C 中是前 8 个字母 "SLOVOSLO"来自“斯洛伐斯洛沃”。字符串 B 类似。

我对算法的想法:

index_A = 0; //index of actual letter of string A
index_B = 0;

Go throught the hole string C from 0 to size(C)
{
  Pick the actual letter from C (C[i])
  if(C[i] == A[index_A] && C[i] != B[index_B])
  {
   index_A++;
   Go to next letter in C 
  }
  else if(C[i] == B[index_B] && C[i] != A[index_A])
  {
   index_B++;
   Go to next letter in C 
  }
  else if(C[i] == B[index_B] && C[i] == A[index_A])
  {
   Now we couldn´t decice which way to go, so we should test both options (maybe recusrsion)
  }
  else
  {
   return false;
  }
}

这只是对算法的快速描述,但我希望你理解这个算法应该做的主要思想。这是解决这个问题的好方法吗?你有更好的解决方案吗?或者一些提示?

【问题讨论】:

  • 你打算用什么语言写这个?
  • 最后是伪代码或者可能是 C 语言。抱歉,我用“非语言”编写代码,但希望你能理解。

标签: string algorithm string-matching prefix repeat


【解决方案1】:

基本上你遇到了每个正则表达式匹配器都有的问题。是的,您需要测试这两个选项,如果其中一个不起作用,您将不得不 backtrack 到另一个选项。递归地在字符串上表达你的循环会有所帮助。

但是,也有一种方法可以同时尝试这两个选项。请参阅热门文章Regular Expression Matching Can Be Simple And Fast 了解这个想法 - 在c 的迭代过程中,您基本上会跟踪两个字符串中所有可能的位置。所需的查找结构的大小为len(A)*len(B),因为您可以只对字符串位置使用模数,而不是将位置存储在无限重复的字符串中。

// some (pythonic) pseudocode for this:

isIntermixedRepetition(a, b, c)
    alen = length(a)
    blen = length(c)
    pos = new Set() // to store tuples
                    // could be implemented as bool array of dimension alen*blen
    pos.add( [0,0] ) // init start pos
    for ci of c
        totest = pos.getContents() // copy and
        pos.clear()                // empty the set
        for [indexA, indexB] of totest
            if a[indexA] == ci
                pos.add( [indexA + 1 % alen, indexB] )
            // no else
            if b[indexB] == ci
                pos.add( [indexA, indexB + 1 % blen] )
        if pos.isEmpty
            break
    return !pos.isEmpty

【讨论】:

  • “同时尝试两个选项”和“跟踪两个字符串中所有可能的位置”是什么意思?你能多写点你的想法吗?我不完全明白。谢谢。
  • 你读过我链接的文章吗?如果是,我会尝试编写一些示例伪代码。
  • 是的,我已经读过了。现在我知道你的意思了。你能给我建议吗,我如何在我的代码中同时尝试这两个选项?或者写一些伪代码的快速描述以便更好地解释?
猜你喜欢
  • 1970-01-01
  • 2018-12-17
  • 2020-02-21
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 2018-12-16
相关资源
最近更新 更多