leetcode 567. Permutation in String 寻找子串 + 滑动窗口

太过爱你忘了你带给我的痛 2022-06-03 04:23 178阅读 0赞

Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string’s permutations is the substring of the second string.

Example 1:
Input:s1 = “ab” s2 = “eidbaooo”
Output:True
Explanation: s2 contains one permutation of s1 (“ba”).
Example 2:
Input:s1= “ab” s2 = “eidboaoo”
Output: False
Note:
The input strings only contain lower case letters.
The length of both given strings is in range [1, 10,000].

本题题意很简单,直接使用一个滑动窗口来做遍历即可

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <numeric>
  14. #include <cmath>
  15. using namespace std;
  16. class Solution
  17. {
  18. public:
  19. bool checkInclusion(string s1, string s2)
  20. {
  21. if (s1.length() > s2.length())
  22. return false;
  23. vector<int> m1(26), m2(26);
  24. for (int i = 0; i < s2.length(); i++)
  25. {
  26. if (i < s1.length())
  27. {
  28. m1[s1[i] - 'a']++;
  29. m2[s2[i] - 'a']++;
  30. }
  31. else
  32. {
  33. if (m1 == m2)
  34. return true;
  35. m2[s2[i] - 'a']++;
  36. m2[s2[i-s1.length()] - 'a']--;
  37. }
  38. }
  39. if (m1 == m2)
  40. return true;
  41. else
  42. return false;
  43. }
  44. };

发表评论

表情:
评论列表 (有 0 条评论,178人围观)

还没有评论,来说两句吧...

相关阅读