为什么80%的码农都做不了架构师?>>>
问题:
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
Note:
- The input strings only contain lower case letters.
- The length of both given strings is in range [1, 10,000].
解决:
① 给定两个字符串s1和s2,问我们s1的全排列的字符串任意一个是否为s2的字串。
虽然题目中有全排列的关键字,但是跟之前的全排列的题目的解法并不一样,如果受思维定势影响比较深的话,很容易遍历s1所有全排列的情况,然后检测其是否为s2的子串,这种解法是非常不高效的,本题本质上可以转换为求在一定范围内(s1长度),字符与s1字符相同的情况是否存在于字符串s2内。
使用滑动窗口Sliding Window的思想来做:
我们先来分别统计s1和s2中前n1个字符串中各个字符出现的次数,其中n1为字符串s1的长度,这样如果二者字符出现次数的情况完全相同,说明s1和s2中前n1的字符互为全排列关系,那么符合题意了,直接返回true。如果不是的话,那么我们遍历s2之后的字符,对于遍历到的字符,对应的次数加1,由于窗口的大小限定为了n1,所以每在窗口右侧加一个新字符的同时就要在窗口左侧去掉一个字符,每次都比较一下两个哈希表的情况,如果相等,说明存在。
class Solution { //26ms
public boolean checkInclusion(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
if(len1 > len2) return false;
int[] h1 = new int[256];
int[] h2 = new int[256];
for (int i = 0;i < len1;i ++){
h1[s1.charAt(i)] ++;
h2[s2.charAt(i)] ++;
}
if (Arrays.equals(h1,h2)) return true;
for (int i = len1;i < len2;i ++){
h2[s2.charAt(i)] ++;
h2[s2.charAt(i - len1)] --;
if (Arrays.equals(h1,h2)) return true;
}
return false;
}
}
② 滑动窗口+hash table + 双指针
class Solution { //15ms
public boolean checkInclusion(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
if(len1 > len2) return false;
int[] hash = new int[256];
for (char c : s1.toCharArray()){
hash[c] ++;
}
int count = len1;
char[] schar = s2.toCharArray();
int left = 0;
int right = 0;
while(right < len2){
if (hash[schar[right ++]] -- > 0) count --;
while(count == 0){
if (right - left == len1) return true;
if (hash[schar[left ++]] ++ == 0) count ++;
}
}
return false;
}
}