567. Permutation in String - Medium

Given two strings s1 and s2, write a function to return true if s2contains 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:

  1. The input strings only contain lower case letters.
  2. The length of both given strings is in range [1, 10,000].

sliding window

time = O(n), space = O(1)

class Solution {
    public boolean checkInclusion(String s1, String s2) {
        int[] map1 = new int[26];
        int[] map2 = new int[26];
        
        for(char c : s1.toCharArray()) {
            map1[c - 'a']++;
        }
        
        int slow = 0, fast = 0;
        while(fast < s2.length()) {
            char cf = s2.charAt(fast);
            map2[cf - 'a']++;
            fast++;
            
            while(fast - slow > s1.length()) {
                char cs = s2.charAt(slow);
                map2[cs - 'a']--;
                slow++;
            }
            
            if(fast - slow == s1.length() && match(map1, map2)) {
                return true;
            }
        }
        return false;
    }
    
    public boolean match(int[] map1, int[] map2) {
        for(int i = 0; i < 26; i++) {
            if(map1[i] != map2[i]) {
                return false;
            }
        }
        return true;
    }
}

猜你喜欢

转载自www.cnblogs.com/fatttcat/p/11386718.html