Skip to content

Latest commit

 

History

History
27 lines (26 loc) · 725 Bytes

File metadata and controls

27 lines (26 loc) · 725 Bytes
  • s1 的字符计数,用滑动窗口检测 s2,若窗口中的子串能用 s1 提供的字符表示,则移动窗口右边界,若不能满足,则移动左边界直至满足,若子串使用了 s1 所有字符,则子串即为 s1 的一个排列
class Solution {
 public:
  bool checkInclusion(string s1, string s2) {
    unordered_map<char, int> m1;
    for (auto& x : s1) {
      ++m1[x];
    }
    int l = 0;
    unordered_map<char, int> m2;
    for (int r = 0; r < size(s2); ++r) {
      char c = s2[r];
      ++m2[c];
      while (m2[c] > m1[c]) {
        --m2[s2[l]];
        ++l;
      }
      if (r - l + 1 == size(s1)) {
        return true;
      }
    }
    return false;
  }
};