#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();
点赞 评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:30
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 11:33
点赞 评论 收藏
分享
程序员小白条:这比例牛逼,750:1
点赞 评论 收藏
分享
昨天 16:52
已编辑
门头沟学院 Java
周五投的,流程今天结束
投递地平线等公司7个岗位
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务