Given two strings s1
and s2
, return true
if s2
contains a permutation of s1
, or false
otherwise.
In other words, return true
if one of s1
's permutations is the substring of s2
.
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
Constraints:
1 <= s1.length, s2.length <= 104
s1
ands2
consist of lowercase English letters.
function checkInclusion(s1: string, s2: string): boolean {
if (s1.length > s2.length) {
return false;
}
const n = s1.length;
const m = s2.length;
const toCode = (s: string) => s.charCodeAt(0) - 97;
const isMatch = () => {
for (let i = 0; i < 26; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
};
const arr1 = new Array(26).fill(0);
for (const s of s1) {
const index = toCode(s);
arr1[index]++;
}
const arr2 = new Array(26).fill(0);
for (let i = 0; i < n; i++) {
const index = toCode(s2[i]);
arr2[index]++;
}
for (let l = 0, r = n; r < m; l++, r++) {
if (isMatch()) {
return true;
}
const i = toCode(s2[l]);
const j = toCode(s2[r]);
arr2[i]--;
arr2[j]++;
}
return isMatch();
}
use std::collections::HashMap;
impl Solution {
fn is_match(m1: &HashMap<char, i32>, m2: &HashMap<char, i32>) -> bool {
for (k, v) in m1.iter() {
if m2.get(k).unwrap_or(&0) != v {
return false;
}
}
true
}
pub fn check_inclusion(s1: String, s2: String) -> bool {
if s1.len() > s2.len() {
return false;
}
let mut m1 = HashMap::new();
let mut m2 = HashMap::new();
for c in s1.chars() {
m1.insert(c, m1.get(&c).unwrap_or(&0) + 1);
}
let cs: Vec<char> = s2.chars().collect();
let mut i = 0;
while i < s1.len() {
m2.insert(cs[i], m2.get(&cs[i]).unwrap_or(&0) + 1);
i += 1;
}
if Self::is_match(&m1, &m2) {
return true;
}
let mut j = 0;
while i < cs.len() {
m2.insert(cs[j], m2.get(&cs[j]).unwrap_or(&1) - 1);
m2.insert(cs[i], m2.get(&cs[i]).unwrap_or(&0) + 1);
j += 1;
i += 1;
if Self::is_match(&m1, &m2) {
return true;
}
}
false
}
}