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

String 基于重复因子的字符串匹配算法,string,algorithm,string-matching,prefix,repeat,String,Algorithm,String Matching,Prefix,Repeat,我有三个字符串作为输入(A、B、C) A=“SLOVO”,B=“WORD”,C= 我需要找到一个算法来决定字符串C是否是无限重复字符串a和B的串联。重复的例子:a^2=“SLOVOSLOVO”,在字符串C中是“SLOVOSLOVO”的前8个字母“SLOVOSLO”。字符串B类似 我对算法的想法: index_A = 0; //index of actual letter of string A index_B = 0; Go throught the hole string C from 0

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

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

我需要找到一个算法来决定字符串C是否是无限重复字符串a和B的串联。重复的例子:a^2=“SLOVOSLOVO”,在字符串C中是“SLOVOSLOVO”的前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
的迭代过程中,您基本上可以跟踪两个字符串中所有可能的位置。所需的查找结构的大小为
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

你打算用什么语言写这篇文章?最后是伪代码,或者可能是C。对不起,我用“非语言”写代码,但我希望你能理解。你说“同时尝试两个选项”和“跟踪两个字符串中所有可能的位置”是什么意思?你能多写些你的想法吗?我不完全明白。Thx.你看过我链接的那篇文章了吗?如果是,我将尝试编写一些示例伪代码。现在我明白你的意思了。你能告诉我,如何在代码中同时尝试这两个选项吗?或者写一些伪代码的快速描述以便更好地解释?