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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)