问题描述
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.
例子
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
方法一
采用固定的窗口,滑动一次检查一次。
** Solution Java **
** 4ms, beats 83.42% **
** 38.9MB, beats 19.23% **
class Solution {
public boolean checkInclusion(String s1, String s2) {
if (s2 == null || s2.length() < s1.length())
return false;
int[] count = new int[26];
for (int i = 0; i < s1.length(); ++i) {
++count[s1.charAt(i) - 'a'];
--count[s2.charAt(i) - 'a'];
}
if (countIsZero(count))
return true;
for (int j = s1.length(); j < s2.length(); ++j) {
--count[s2.charAt(j) - 'a'];
++count[s2.charAt(j - s1.length()) - 'a'];
if (countIsZero(count))
return true;
}
return false;
}
private boolean countIsZero (int[] count) {
for (int i = 0; i < 26; ++i)
if (count[i] != 0)
return false;
return true;
}
}
** Solution Python3 **
** 72ms, beats 62.30% **
** 12.9MB, beats 100.00% **
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if (s2 == None or len(s2) < len(s1)) :
return False
count = [0 for _ in range(26)]
for i in range(len(s1)) :
count[ord(s1[i]) - ord('a')] += 1
count[ord(s2[i]) - ord('a')] -= 1
if (self.isZero(count)) :
return True
for i in range(len(s1), len(s2)) :
count[ord(s2[i]) - ord('a')] -= 1
count[ord(s2[i - len(s1)]) - ord('a')] += 1
if (self.isZero(count)) :
return True
return False
def isZero(self, count):
for i in range(26) :
if (count[i] != 0) :
return False
return True
方法二
** Solution Java **
** 3ms, 99.10% **
** 39MB, 19.23% **
class Solution {
public boolean checkInclusion(String s1, String s2) {
int[] count = new int[128];
for (int i = 0; i < s1.length(); ++i)
--count[s1.charAt(i)];
for (int l = 0, r = 0; r < s2.length(); ++r) {
if (++count[s2.charAt(r)] > 0)
while (--count[s2.charAt(l++)] != 0) {}
else if (r - l + 1 == s1.length())
return true;
}
return s1.length() == 0;
}
}