#include <iostream> (30316)#include <unordered_map> #include <cassert> // 使用标准命名空间 using namespace std; bool isPermutationSubstring(const string& s1, const string& s2) { size_t len_s1 = s1.length(); size_t len_s2 = s2.length(); // 如果s1的长度大于s2,不可能是子串 if (len_s1 > len_s2) { return false; } // 使用哈希表存储字符计数 unordered_map<char, int> charCountS1; unordered_map<char, int> charCountWindow; // 初始化s1的字符计数 for (size_t i = 0; i < len_s1; ++i) { ++charCountS1[s1[i]]; ++charCountWindow[s2[i]]; } // 滑动窗口 for (size_t i = 0; i < len_s2 - len_s1; ++i) { if (charCountS1 == charCountWindow) { return true; } // 移动窗口 ++charCountWindow[s2[i + len_s1]]; --charCountWindow[s2[i]]; } // 最后一次比较 return charCountS1 == charCountWindow; } // 测试函数 void check() { assert(isPermutationSubstring("abc", "cbabadcbbabbcbabaabccbabc") == true); assert(isPermutationSubstring("test", "esttest") == true); assert(isPermutationSubstring("hello", "world") == false); assert(isPermutationSubstring("a", "ab") == true); assert(isPermutationSubstring("aa", "a") == false); cout << "All tests passed!" << endl; } // 如果不需要主函数,可以将测试函数直接放在代码末尾 check();
点赞 评论

相关推荐

牛客网
牛客企业服务