确定性自动机在另一个字符串的字符串中查找子序列的数量

时间:2014-01-26 17:12:18

标签: string algorithm theory dfa subsequence

确定性自动机在字符串中查找子序列的数量? 如何构造DFA以查找出现的字符串数作为另一个字符串中的子序列?

例如。在“ssstttrrriiinnngggg”中,我们有3个子序列,形成字符串“string”?

要查找和要搜索的字符串也只包含特定字符集中的字符。 我有一些想法在堆栈中存储字符,相应地弹出它们直到我们匹配,如果再次匹配不匹配。 请告诉DFA解决方案?

1 个答案:

答案 0 :(得分:0)

重叠比赛

如果您想计算重叠序列的数量,那么您只需构建一个与字符串匹配的DFA,例如

1 - (如果看到s) - > 2 - (如果看到t) - > 3 - (如果见r) - > 4 - (如果见i) - > 5 - (如果见n) - > 6 - (如果见g) - > 7

然后使用动态编程计算每个角色后计算每种状态的方式数。有关详细信息,请参阅此question的答案。

DP[a][b] = number of ways of being in state b after seeing the first a characters
         = DP[a-1][b] + DP[a-1][b-1] if character at position a is the one needed to take state b-1 to b
         = DP[a-1][b] otherwise

从DP [0] [b] = 0开始,b> 1且DP [0] [1] = 1。

然后重叠字符串的总数是DP [len(string)] [7]

非重叠比赛

如果你计算非重叠序列的数量,那么如果我们假设要匹配的模式中的字符是不同的,我们可以稍作修改:

DP[a][b] = number of strings being in state b after seeing the first a characters
         = DP[a-1][b] + 1 if character at position a is the one needed to take state b-1 to b and  DP[a-1][b-1]>0
         = DP[a-1][b] - 1 if character at position a is the one needed to take state b to b+1 and DP[a-1][b]>0
         = DP[a-1][b] otherwise

从DP [0] [b] = 0开始,b> 1且DP [0] [1] =无穷大。

然后非重叠字符串的总数是DP [len(string)] [7]

如果要匹配的模式包含重复的字符(例如“字符串”),则此方法不一定能给出正确的答案。