O(n)时间O(1)空间子串搜索与括号模式

时间:2012-08-19 04:14:28

标签: regex language-agnostic pattern-matching substring

对于固定子串搜索,有两种已知的算法具有O(n)运行时和O(1)工作空间:SMOA和双向(参见http://www-igm.univ-mlv.fr/~lecroq/string/)。它们都取决于在字母表上加上或强制订购。

假设不是搜索固定的子串,而是希望能够搜索用括号表达式表示的一组子串中的任何一个,例如。

 [abc]d

将匹配“ad”,“bd”或“cd”。假设字母表是有限的,任何括号的长度都是有界的,因此在时间或空间要求中形式为“括号长度”的任何术语都是O(1)。

有没有办法在O(n)时间内执行搜索(其中n是要搜索的字符串的长度,即“haystack”)和O(1)工作空间?

除非解决方案涉及以字母顺序排序括号集,否则该问题的任何解决方案将为O(n)/ O(1)中的固定子串搜索问题提供新的解决方案,而无需排序要求,因此似乎不太可能存在。

1 个答案:

答案 0 :(得分:0)

我一定错过了什么。从您的链接页面,强力方法是O(n)。看起来你可以轻松地写出你想要的东西:

1.  Pattern is P with index p indicating which element of the pattern we are on.
2.  String is S with index s indicating which element of the string we are on.
3.  if S[s] matches P[p], increment both indicies and repeat until you complete the Pattern.
4.  If S[s] doesn't match P[p], set p=0 and increment p.

那将是O(n)并满足您的要求。

相关问题