Skip to content

Latest commit

 

History

History
152 lines (118 loc) · 3.47 KB

File metadata and controls

152 lines (118 loc) · 3.47 KB

题目描述

给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的某个变位词。

换句话说,第一个字符串的排列之一是第二个字符串的 子串

 

示例 1:

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

示例 2:

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

 

提示:

  • 1 <= s1.length, s2.length <= 104
  • s1s2 仅包含小写字母

 

注意:本题与主站 567 题相同: https://leetcode-cn.com/problems/permutation-in-string/

解法

维护一个长度固定的窗口向前滑动

Python3

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        n1, n2 = len(s1), len(s2)
        if n1 > n2:
            return False
        window = [0 for _ in range(26)]
        for i in range(n1):
            window[ord(s1[i]) - ord('a')] += 1
            window[ord(s2[i]) - ord('a')] -= 1
        if self.check(window): return True
        for i in range(n1, n2):
            window[ord(s2[i]) - ord('a')] -= 1
            window[ord(s2[i - n1]) - ord('a')] += 1
            if self.check(window): return True
        return False

    def check(self, window: List[int]) -> bool:
        return all([cnt == 0 for cnt in window])

Java

class Solution {
    public boolean checkInclusion(String s1, String s2) {
        int n1 = s1.length(), n2 = s2.length();
        if (n1 > n2) {
            return false;
        }
        int[] window = new int[26];
        for (int i = 0; i < n1; i++) {
            window[s1.charAt(i) - 'a']++;
            window[s2.charAt(i) - 'a']--;
        }
        if (check(window)) {
            return true;
        }
        for (int i = n1; i < n2; i++) {
            window[s2.charAt(i) - 'a']--;
            window[s2.charAt(i - n1) - 'a']++;
            if (check(window)) {
                return true;
            }
        }
        return false;
    }

    private boolean check(int[] window) {
        return Arrays.stream(window).allMatch(cnt -> cnt == 0);
    }
}

Go

func checkInclusion(s1 string, s2 string) bool {
	n1, n2 := len(s1), len(s2)
	if n1 > n2 {
		return false
	}
	window := make([]int, 26)
	for i := 0; i < n1; i++ {
		window[s1[i]-'a']++
		window[s2[i]-'a']--
	}
	if check(window) {
		return true
	}
	for i := n1; i < n2; i++ {
		window[s2[i]-'a']--
		window[s2[i-n1]-'a']++
		if check(window) {
			return true
		}
	}
	return false
}

func check(window []int) bool {
	for _, cnt := range window {
		if cnt != 0 {
			return false
		}
	}
	return true
}

...