在字符串范围列表中搜索字符串
search for a string in a list of string ranges
例如,我有一个词典范围列表[a,an) [an,bb) [bb,d) [c,h)
给定一个字符串,比如apple
,我需要找到它属于哪个范围。在这种情况下,它在第二个范围内。如果字符串可能属于多个范围,则需要返回第一个范围。例如:cat
应该返回range3而不是range4。
粗暴的方法是按顺序循环列表,并检查字符串是否适合其中。更好的方法是先解决重叠,对范围进行排序,然后进行二进制搜索。对进一步优化算法有什么建议吗?另外,欢迎使用c++的实现技巧。这种逻辑恰好发生在关键的执行路径上,并且必须快速。
更新:是的,范围可能存在差距。是的,二进制搜索可以使它成为O(log(n))
。有没有什么方法可以让我想出一个杂烩,让它变得更好?杂碎会是什么样子?我们可以假设在所有字符串和范围中只有小写字符。
以下是您应该做的:
首先按照字典顺序对范围的开头进行排序。然后,您应该对它们进行以下预处理-对于每个范围,使其开始于上一个范围的开始和结束中较大的一个(如果这使当前范围为空,则忽略它)。你这样做是因为如果一个单词在前一个范围的末尾之前,那么它将属于前一个区域中的一些区域,并且永远不会被分类到当前区域中。在这个预处理之后,所有的范围都是不重叠的,所以你搜索的每个单词最多只属于其中一个。因此,您所需要做的就是对生成的预处理范围执行二进制搜索,该范围的复杂性为O(log(n))。我怀疑你能否把这个问题的复杂性提高。
对每个范围的开头进行某种索引,也许是一个二进制树,可能是个好主意。不确定是否需要索引到每个范围的末尾,除非可能存在间隙。
我想到了一个解决方案,可能是你可以对单词apple进行排序,并识别a-z顺序中最后一个的字符。只需检查你范围内的那一个字符。思考更多。。。
如果您有多余的内存,并且限制为小写,则可以构建一个多路树。顶部节点有一个由26个指针组成的数组。如果没有以该字符开头的范围,则指针为Null。如果所有以该字符开头的单词都属于某个范围,则它们指向该范围;如果范围在下一个字符上拆分,则它们会指向另一个节点。(因此,给定[a-ap],[arbl];"a"条目将指向另一个节点,其中条目"a"到"p"指向范围1,条目"q"为null,条目"r"到"z"指向范围2。)
这应该是O(max(range_specifier))。
您可以通过"网格化"来实现这一点。
使用一个数组,其中26个条目对应于第一个字母。每个bin都包含与之有非空交集的范围列表
'a' -> [a,an) [an,bb), 'b' -> [an,bb) [bb,d), 'c' -> [bb,d) [c,h) ...
你可以很容易地将这个想法概括为几个字母的前缀
'aaa' -> [a,an), 'aab' -> [a,an), 'aac' -> [a,an) ...
这可以大大缩短要尝试的范围列表,尤其是在几乎没有重叠的情况下,以牺牲存储和预处理时间为代价。
一个特殊的约定可以用来表示垃圾箱被完全覆盖。
我想,快乐的分配可以导致O(1)。
如果您的范围集可以用trie表示,我不会感到惊讶(http://en.wikipedia.org/wiki/Trie)。一旦trie被填充,查询时间就不应该超过最长范围绑定的长度,也不应该超过查询字符串的长度。
就查询时间而言,这是最优的(事实上,在您的计算模型中为O(1))。
我的方法是
- 一个范围有两个极限(下限和上限)
- 每个范围将空间分成三部分(下面、里面、上面)
- 每个极限将空间分成两部分(下,上或相等)
因此方法可以是:
- 对范围进行编号
- 将范围分解为两个极限
- 将限制放入一个树中,在包含两个列表的节点中,这些列表包含引用它们的范围(一个列表用于将该限制用作下限的节点,一个列表表示上限)
- 这些列表可以是位图,因为范围是有编号的
- 查找字符串
- 你走在树上,每次你走下树,你都会越过一个极限,了解你的右边/左边有哪些极限,你在左边/右边/里面有哪些范围
- 您需要两个额外的(范围号的)列表来进行遍历
- 这些列表可以是位图
- 每次越过边界时,都要从其中一个列表中添加范围号,然后从另一个列表中将其删除
- 一旦你在一个范围内(x>=下限&x<上限;,当然限制对应于相同的范围),algor.htm就结束了。
- (假设这实际上是数字最低的范围:第一匹配)
- 如果两个列表共享一个或多个成员,则可以检测到这一点
- 我们想要编号最低的重叠成员
由于该方法是一种树搜索,因此它具有O(log(N))的复杂性。
更新:仔细想想,位图不是存储使用列表或结果的好方法。链表(实际上是两个)更好。代码是300行。我应该把它贴在这里吗?
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define COUNTOF(a) (sizeof a / sizeof a[0])
#define WANT_DUPLICATES 0
struct range {
/* separate linked lists for {lo,hi})
** for limits that this range participates in. */
struct range *next_lo;
struct range *next_hi;
unsigned num;
char *str_lo, *str_hi;
} ranges[] =
{{NULL,NULL,0, "a","an"}, {NULL,NULL,1, "an", "bb"}
,{NULL,NULL,2, "bb", "d"}, {NULL,NULL,3, "c", "h"}
,{NULL,NULL,4, "bb", "c"}, {NULL,NULL,5, "c", "d"}
};
#define NRANGE COUNTOF(ranges)
void add_range(struct range *pp);
void list_dmp(FILE *fp, int isupper, struct range *bp);
struct treetwo {
struct treetwo *prev;
struct treetwo *next;
char *str;
struct range *list_lo; /* ranges that use str as lower limit */
struct range *list_hi; /* ranges that use str as upper limit */
};
struct treetwo *root = NULL;
struct treetwo ** find_hnd(struct treetwo **tpp, char *str);
void tree_dmp(FILE *fp, struct treetwo *tp, char *msg, unsigned indent);
struct result {
unsigned size;
unsigned used;
struct {
unsigned num;
unsigned mask;
} *entries;
};
#define MASK_BELOW_LO 1
#define MASK_ABOVE_LO 2
#define MASK_BELOW_HI 4
#define MASK_ABOVE_HI 8
int result_resize(struct result *res, unsigned newsize);
void init_structures(void);
struct result *find_matches (char *str);
unsigned update_state(struct result *rp, struct treetwo *tp, int isabove);
int main (void)
{
char buff[100];
struct result *res;
size_t pos;
unsigned idx;
static char *legend[4] = { "unknown", "below", "above", "impossible"};
init_structures();
tree_dmp(stderr, root, "Root", 0);
while (fgets (buff, sizeof buff, stdin) ) {
pos=strcspn(buff, "rn");
buff[pos] = 0;
res = find_matches (buff);
for (idx=0; idx < res->used; idx++) {
unsigned num = res->entries[idx].num;
unsigned mask = res->entries[idx].mask;
fprintf(stdout, "[%u]Range%u %x: '%s' %s '%s' and '%s' %s '%s'n"
, idx, num, mask
, buff, legend[mask & 3], ranges[num].str_lo
, buff, legend[(mask>>2) & 3], ranges[num].str_hi
);
}
}
return 0;
}
unsigned update_state(struct result *rp, struct treetwo *tp, int isabove)
{
struct range *p;
unsigned mask_lo, mask_hi;
unsigned hitcnt,idx;
/* State: (lower limit)
** 0 : unknown
** MASK_BELOW_LO: below limit
** MASK_ABOVE_LO: above limit
** 3: impossible
** State: (upper limit)
** 0 : unknown
** MASK_BELOW_HI: below limit
** MASK_ABOVE_HI: above limit
** c: impossible
** Combined states:
** required state 2|4 := 6
** 5: unreachable
** a: unreachable
** 9: impossible
** f: impossible
*/
if (!tp) return 0;
hitcnt=0;
mask_lo = (isabove>=0) ? MASK_ABOVE_LO : MASK_BELOW_LO;
mask_hi = (isabove>=0) ? MASK_ABOVE_HI : MASK_BELOW_HI;
fprintf(stderr , "Update_state(start{%s}, isabove=%d, mask=%x,%x)n"
, tp->str , isabove, mask_lo, mask_hi);
fprintf(stderr , "Update_state(Lo=%s)=", tp->str);
list_dmp(stderr , 0, tp->list_lo);
idx=0;
for (p = tp->list_lo; p ; p = p->next_lo) {
unsigned num = p->num;
fprintf(stderr , "Update_state:[%u] |= %u", num, mask_lo );
for ( ;idx < rp->used;idx++) { if (rp->entries[idx].num >= num) break; }
if ( idx < rp->used ) {
fprintf(stderr , " Old was:%un", rp->entries[idx].mask );
rp->entries[idx].mask |= mask_lo;
if (rp->entries[idx].mask == (MASK_ABOVE_LO|MASK_BELOW_HI)) hitcnt++;
continue;
}
if ( idx >= rp->used) {
if ( rp->used >= rp->size && result_resize(rp, rp->size ? rp->size*2 : 8)) break;
fprintf(stderr , " New at:%un", idx );
rp->entries[idx].num = num;
rp->entries[idx].mask = mask_lo;
rp->used++;
}
}
fprintf(stderr , "Update_state(Hi=%s)=", tp->str);
list_dmp(stderr , 1, tp->list_hi);
idx=0;
for (p = tp->list_hi; p ; p = p->next_hi) {
unsigned num = p->num;
fprintf(stderr , "Update_state:[%u] |= %u", num, mask_lo );
for ( ;idx < rp->used;idx++) { if (rp->entries[idx].num >= num) break; }
if ( idx < rp->used ) {
fprintf(stderr , " Old was:%un", rp->entries[idx].mask );
rp->entries[idx].mask |= mask_hi;
if (rp->entries[idx].mask == (MASK_ABOVE_LO|MASK_BELOW_HI)) hitcnt++;
continue;
}
if ( idx >= rp->used) {
if ( rp->used >= rp->size && result_resize(rp, rp->size ? rp->size*2 : 8)) break;
fprintf(stderr , " New at:%un", idx );
rp->entries[idx].num = num;
rp->entries[idx].mask = mask_hi;
rp->used++;
}
}
return hitcnt;
}
struct result *find_matches (char *str)
{
int rc;
struct treetwo **hnd;
struct result *res = malloc (sizeof *res);
unsigned dst,src;
res->used=res->size=0; res->entries=0;
for (hnd= &root; *hnd; hnd = (rc < 0) ? &(*hnd)->prev : &(*hnd)->next ) {
rc = strcmp( str, (*hnd)->str);
fprintf(stderr, "####nStr=%s Node={%s} rc=%dn"
, str, (*hnd)->str, rc );
list_dmp(stderr , 0, (*hnd)->list_lo );
list_dmp(stderr , 1, (*hnd)->list_hi );
rc = update_state(res, *hnd , rc);
#if WANT_DUPLICATES
continue;
#else
/* if we don't want duplicates we can bail out on the first match */
if (rc) break;
#endif
}
/* Now cleanup the results.
** Below(lower limit) and above(upper limit) and variations can be removed.
** Some results are incomplete, because one of there limits is out
** of reach (shadowed by a narrower range). We'll have to recompute these.
** The result structure is compacted: if entries are deleted, the remaining ones are shifted down.
** Note: part of this cleanup (removal of unreacheables) could be done in update_state(),
** that would keep the array with partial results as short as possible.
*/
for (dst=src=0; src < res->used; src++) {
int rc;
unsigned num = res->entries[src].num;
rescan:
switch (res->entries[src].mask & 0xf) {
default: break;
case 0: /* impossible */
goto rescan;
#if WANT_DUPLICATES
case MASK_ABOVE_LO:
rc = strcmp(str, ranges[num].str_hi);
res->entries[src].mask |= (rc >=0) ? MASK_ABOVE_HI : MASK_BELOW_HI;
goto rescan;
case MASK_BELOW_HI:
rc = strcmp(str, ranges[num].str_lo);
res->entries[src].mask |= (rc >=0) ? MASK_ABOVE_LO : MASK_BELOW_LO;
goto rescan;
#endif
case MASK_BELOW_HI|MASK_ABOVE_LO:
if (dst != src) res->entries[dst] = res->entries[src];
dst++;
}
}
fprintf(stderr, "####nFinal pass: %u/%un", dst, res->used );
res->used = dst;
return res;
}
void init_structures(void)
{
unsigned idx;
for (idx = 0; idx < NRANGE; idx++) {
add_range( &ranges[idx]);
}
}
void list_dmp(FILE *fp, int isupper, struct range *bp)
{
fprintf(fp, "%s", (isupper) ? "Upper" :"Lower" );
for ( ; bp ; bp = (isupper) ? bp->next_hi : bp->next_lo) {
fprintf(fp, " %u:{%s,%s}"
, bp->num , bp->str_lo , bp->str_hi
);
}
fprintf( stdout, "n" );
}
void add_range(struct range *pp)
{
struct treetwo **tpp;
struct range **rpp;
fprintf(stderr, "Inserting range %u->{%s,%s}n", pp->num, pp->str_lo, pp->str_hi);
/* find low boundary for this interval */
tpp = find_hnd (&root, pp->str_lo);
if (!*tpp) {
fprintf(stderr, "Creating node for %u->%s (low)n", pp->num, pp->str_lo);
*tpp = malloc(sizeof **tpp);
(*tpp)->list_lo = NULL;
(*tpp)->list_hi = NULL;
(*tpp)->str = pp->str_lo;
}
for (rpp = &(*tpp)->list_lo; *rpp ; rpp = &(*rpp)->next_lo) {;}
*rpp = pp;
fprintf(stderr, "Added range %u->{%s,%s} to treenode(%s)->list_lon"
, pp->num, pp->str_lo, pp->str_hi
, (*tpp)->str
);
/* find high boundary */
tpp = find_hnd (&root, pp->str_hi);
if (!*tpp) {
fprintf(stderr, "Creating node for %u->%s (High)n", pp->num, pp->str_hi);
*tpp = malloc(sizeof **tpp);
(*tpp)->list_lo = NULL;
(*tpp)->list_hi = NULL;
(*tpp)->str = pp->str_hi;
}
for (rpp = &(*tpp)->list_hi; *rpp ; rpp = &(*rpp)->next_hi) {;}
*rpp = pp;
fprintf(stderr, "Added range %u->{%s,%s} to treenode(%s)->list_hin"
, pp->num, pp->str_lo, pp->str_hi
, (*tpp)->str
);
}
struct treetwo ** find_hnd(struct treetwo **tpp, char *str)
{
int rc;
for ( ; *tpp; tpp = (rc < 0) ? &(*tpp)->prev : &(*tpp)->next ) {
rc = strcmp( str, (*tpp)->str);
if (!rc) break;
}
return tpp;
}
void tree_dmp(FILE *fp, struct treetwo *tp, char *msg, unsigned indent)
{
unsigned uu;
if (!tp) return;
if (!msg) msg = "";
for (uu=0; uu < indent; uu++) { fputc( ' ', fp); }
fprintf(fp, "%s:{%s}n", msg, tp->str );
for (uu=0; uu < indent+1; uu++) { fputc( ' ', fp); }
list_dmp(fp , 0, tp->list_lo);
for (uu=0; uu < indent+1; uu++) { fputc( ' ', fp); }
list_dmp(fp , 1, tp->list_hi);
tree_dmp(fp, tp->prev, "Prev", indent+2);
tree_dmp(fp, tp->next, "Next", indent+2);
}
int result_resize(struct result *res, unsigned newsize)
{
void *old;
old = res->entries;
res->entries = realloc ( res->entries , newsize * sizeof *res->entries);
if ( !res->entries) {
res->entries = old; return -1;
}
res->size = newsize;
if (res->used > newsize) res->used = newsize;
return 0;
}
- 哪个更快:在 1d 向量中按字符串搜索还是在 2d 向量中按向量搜索?
- 有序地图字符串搜索与整数搜索之间的时间复杂度
- 使用图形的字符串搜索算法?C++
- C++子字符串搜索 - 跳入C++
- 字符串搜索 - 并行版本较慢
- 使用Robert Sedwick书中的符号表进行字符串搜索
- C++中的部分字符串搜索
- 哪个是更好的字符串搜索算法?Boyer-Moore或Boyer Moore Horspool
- 如何使用 c++ 将字符串搜索到字符串数组中
- 使用 C++ 在文件中进行字符串搜索/索引
- Qt5 中字符串搜索的最佳容器
- 优化.txt文件中的字符串搜索
- 字符串搜索输入中包含的单词
- Boyer-Moore-坏字符规则实现子字符串搜索
- 带星号*通配符的字符串搜索
- c++字符串搜索函数
- 最好的字符串搜索算法
- 通配符字符串搜索算法
- 在c++中使用字符串(搜索字符串,分割字符串,cout<<字符串)
- Strstr()函数重叠字符串搜索