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 <= 10^4
s1
and s2
consist of lowercase English letters.使用字典保存s1中所有字符的数量,使用滑动窗口遍历s2,使用字典保存窗口中的值,当s1字典和s2字典相同时,则返回true,否则在遍历结束后返回false。
python版本:
class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: s1_map = {} s2_map = {} for i in s1: if i in s1_map: s1_map[i] += 1 else: s1_map[i] = 1 start = 0 for now in s2: if now in s1_map and (now not in s2_map or s2_map[now] < s1_map[now]): if now not in s2_map: s2_map[now] = 1 else: s2_map[now] += 1 equal = True for k, v in s1_map.items(): if k not in s2_map or s2_map[k] != v: equal = False break if equal: return True else: while s2[start] != now: if s2[start] in s2_map: s2_map[s2[start]] -= 1 start += 1 start += 1 return False