【发布时间】:2013-10-10 12:05:49
【问题描述】:
例如。单词是for,文本是forxxorfxdofr,for 的字谜将是ofr、orf、fro 等。所以对于这个特定的例子,答案是3。
这是我想出的。
#include<iostream>
#include<cstring>
using namespace std;
int countAnagram (char *pattern, char *text)
{
int patternLength = strlen(pattern);
int textLength = strlen(text);
int dp1[256] = {0}, dp2[256] = {0}, i, j;
for (i = 0; i < patternLength; i++)
{
dp1[pattern[i]]++;
dp2[text[i]]++;
}
int found = 0, temp = 0;
for (i = 0; i < 256; i++)
{
if (dp1[i]!=dp2[i])
{
temp = 1;
break;
}
}
if (temp == 0)
found++;
for (i = 0; i < textLength - patternLength; i++)
{
temp = 0;
dp2[text[i]]--;
dp2[text[i+patternLength]]++;
for (j = 0; j < 256; j++)
{
if (dp1[j]!=dp2[j])
{
temp = 1;
break;
}
}
if (temp == 0)
found++;
}
return found;
}
int main()
{
char pattern[] = "for";
char text[] = "ofrghofrof";
cout << countAnagram(pattern, text);
}
是否存在针对上述问题的更快算法?
【问题讨论】:
-
是否允许重叠字谜?如果文字是
frof,答案是1还是2? -
在这种情况下答案是 2。
-
我可能没抓住重点,但你为什么不直接在字符串中搜索“for”的字谜呢?你的逻辑似乎很复杂
-
我不确定您提出的是什么算法。但是您的算法似乎具有时间复杂度 O(NM),其中 N = 文本长度,M = 模式长度。
-
在网上搜索“c++ anagramefficient”