Careercup

2014-05-02 01:05

题目链接

原题:

bool anaStrStr (string needle, string haystack) 
{
}

Write a function that takes 2 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至多扫描完整个文本串,保证算法是严格线性的。

代码:

 1 // http://www.careercup.com/question?id=5671785349513216
 2 #include <iostream>
 3 #include <string>
 4 #include <vector>
 5 using namespace std;
 6 
 7 class Solution {
 8 public:
 9     bool anaStrStr (string needle, string haystack) {
10         int len1, len2;
11         
12         len1 = (int)needle.length();
13         len2 = (int)haystack.length();
14         
15         if (len1 == 0) {
16             return true;
17         } else if (len2 < len1) {
18             return false;
19         }
20         
21         memset(cn, 0, 256 * sizeof(int));
22         memset(ch, 0, 256 * sizeof(int));
23         int i, j;
24 
25         cc = 0;
26         for (i = 0; i < len1; ++i) {
27             ++cn[needle[i]];
28             ++cc;
29         }
30         
31         i = 0;
32         j = i;
33         while (true) {
34             if (cc == 0) {
35                 return true;
36             }
37 
38             if (i > len2 - len1) {
39                 return false;
40             }
41             
42 
43             if (ch[haystack[j]] < cn[haystack[j]]) {
44                 ++ch[haystack[j]];
45                 --cc;
46                 ++j;
47             } else {
48                 while (i <= j && ch[haystack[j]] == cn[haystack[j]]) {
49                     if (ch[haystack[i]] > 0) {
50                         --ch[haystack[i]];
51                         ++cc;
52                     }
53                     ++i;
54                 }
55                 j = i > j ? i : j;
56             }
57         }
58     };
59 private:
60     int cn[256], ch[256];
61     int cc;
62 };
63 
64 int main()
65 {
66     string needle, haystack;
67     Solution sol;
68     
69     while (cin >> needle >> haystack) {
70         cout << (sol.anaStrStr(needle, haystack) ? "true" : "false") << endl;
71     }
72     
73     return 0;
74 }
原文地址:https://www.cnblogs.com/zhuli19901106/p/3703589.html