Careercup - Facebook面试题 - 5671785349513216

时间:2022-06-23 10:08:20

2014-05-02 01:05

题目链接

原题:

bool anaStrStr (string needle, string haystack)
{
} Write a function that takes strings , search returns true if any anagram of string1(needle) is present in string2(haystack)

题目:写一个字符串匹配的函数,但是要求只要能在文本里找到模式的anagram,就返回true。

解法:对于anagram这词的翻译实在是无力吐槽,居然叫“字谜”。所以不翻译反而更省事。因为要匹配的是模式的所有anagram,我们不需要像KMP算法那样计算模式的失配跳转位置,就可以完成O(n)时间内的算法。我们需要随时维护的,是模式串的字符统计,以及当前文本串的字符统计。我们需要一左一右两个iterator,统计两个iterator之间的字串的字母构成情况。开始两者都在0位置,各个字符统计数也都为0。在扫描过程中,如果数量不足,则右端iterator一直向右移动;如果某个字符数量超过了模式串,则左端iterator一直向右移动。这样的话,两个iterator至多扫描完整个文本串,保证算法是严格线性的。

代码:

 // http://www.careercup.com/question?id=5671785349513216
#include <iostream>
#include <string>
#include <vector>
using namespace std; class Solution {
public:
bool anaStrStr (string needle, string haystack) {
int len1, len2; len1 = (int)needle.length();
len2 = (int)haystack.length(); if (len1 == ) {
return true;
} else if (len2 < len1) {
return false;
} memset(cn, , * sizeof(int));
memset(ch, , * sizeof(int));
int i, j; cc = ;
for (i = ; i < len1; ++i) {
++cn[needle[i]];
++cc;
} i = ;
j = i;
while (true) {
if (cc == ) {
return true;
} if (i > len2 - len1) {
return false;
} if (ch[haystack[j]] < cn[haystack[j]]) {
++ch[haystack[j]];
--cc;
++j;
} else {
while (i <= j && ch[haystack[j]] == cn[haystack[j]]) {
if (ch[haystack[i]] > ) {
--ch[haystack[i]];
++cc;
}
++i;
}
j = i > j ? i : j;
}
}
};
private:
int cn[], ch[];
int cc;
}; int main()
{
string needle, haystack;
Solution sol; while (cin >> needle >> haystack) {
cout << (sol.anaStrStr(needle, haystack) ? "true" : "false") << endl;
} return ;
}