滑动窗口-字符串的排列

63 阅读1分钟

567. 字符串的排列

给你两个字符串 s1 和 s2 ,写一个函数来判断 s2 是否包含 s1 ****的排列。如果是,返回 true ;否则,返回 false 。

换句话说,s1 的排列之一是 s2 的 子串 。

 

示例 1:

输入: s1 = "ab" s2 = "eidbaooo"
输出: true
解释: s2 包含 s1 的排列之一 ("ba").

示例 2:

输入: s1= "ab" s2 = "eidboaoo"
输出: false

 

提示:

  • 1 <= s1.length, s2.length <= 104
  • s1 和 s2 仅包含小写字母
/**
 * @param {string} s1
 * @param {string} s2
 * @return {boolean}
 */
var checkInclusion = function(s1, s2) {
	const targetMap = {};
	for (const ch of s1) {
		targetMap[ch] = (targetMap[ch] || 0) + 1;
	}

	const targetMapLen = Object.keys(targetMap).length;
	const curMap = {};

	let result = false;
	for (let left = 0, right = 0; right < s2.length; right++) {
		curMap[s2[right]] = (curMap[s2[right]] || 0) + 1;
 		while (left <= right && (!targetMap[s2[left]] || curMap[s2[left]] > targetMap[s2[left]])) {
 			curMap[s2[left]]--;
 			if (curMap[s2[left]] === 0) {
 				delete curMap[s2[left]];
 			}
 			left++;
 		}
        
 		const curMapKeys = Object.keys(curMap);
 		if (targetMapLen === curMapKeys.length) {
            result = true;
 			curMapKeys.forEach(key => {
 				if (curMap[key] !== targetMap[key]) {
 					result = false;
 				}
 			})
 		}

 		if (result) {
 			break;
 		}
	}

	return result;
};