From 3719fb0a11dc2d816ca17741a04c614fece6ea82 Mon Sep 17 00:00:00 2001 From: juan Date: Thu, 14 Jul 2022 11:03:17 +0800 Subject: [PATCH] vault backup: 2022-07-14 11:03:17 --- .../pages/Leetcode Permutation-In-String.md | 43 ++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/OJ notes/pages/Leetcode Permutation-In-String.md b/OJ notes/pages/Leetcode Permutation-In-String.md index f8d4fce..6edbd74 100644 --- a/OJ notes/pages/Leetcode Permutation-In-String.md +++ b/OJ notes/pages/Leetcode Permutation-In-String.md @@ -53,6 +53,47 @@ In other words, return `true` if one of `s1`'s permutations is the substring of I tried to use kadane's algorithm, but the problem is a premature string, not set. So I gave up. - +Then I found out this is sliding window problem, similar to +[[Leetcode Longest-Substring-Without-Repeating-Characters]] ### Solution + +```cpp +class Solution { +public: + bool checkInclusion(string s1, string s2) { + // Sliding windows problem. + + // First, register the freqs of s1 + vector freq(26, 0); + for (char ch : s1) { + freq[ch - 'a']++; + } + + // Second, start constructing window and window freq; + int len = s1.length(); + int l = 0, r = 0; + vector window(26, 0); + + // Start expanding and sliding! + while (r < s2.length()) { + // I add value to window here, to avoid r OOB when r = s2.length + window[s2[r] - 'a']++; + if (r - l + 1 < len) { + // Expand right + r++; + } else if (window == freq) { // note that I use else if, to make sure + // every time r is incremented once. + return true; + } else { + // Remove l from the window, slide right + window[s2[l] - 'a']--; + l++; + r++; + } + } + + return false; + } +}; +``` \ No newline at end of file