算法 - 基于重复因子的字符串匹配

时间:2014-05-12 16:36:58

标签: string algorithm string-matching prefix repeat

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

A =“SLOVO”,B =“WORD”,C =

enter image description here

我需要找到算法,如果字符串C是无限重复字符串A和B的串联,则重复的例子:A ^ 2 =“SLOVOSLOVO”,字符串C是前8个字母“SLOVOSLO”来自“SLOVOSLOVO”。字符串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;
  }
}

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

1 个答案:

答案 0 :(得分:2)

基本上你已经遇到了每个正则表达式匹配器都有的问题。是的,你需要测试这两个选项,如果一个人没有工作,你将需要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