Leetcode之Permutation in String 问题

问题描述:

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.

Note:

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

示例一:

Input:s1 = "ab" s2 = "eidbaooo"
Output:True
Explanation: s2 contains one permutation of s1 ("ba").

示例二:

Input:s1= "ab" s2 = "eidboaoo"
Output: False

题目来源:Permutation in String (详细地址:https://leetcode.com/problems/permutation-in-string/description/)

思路分析:

       首先搞懂题目的意思,示例一返回的结果是true,表明s1在s2中不按顺序出现照样是能返回正确结果的。接着,我们看看如果s1中出现过的字符,要返回结果为true,那么s2中肯定也出现了才能行。所以,我们需要一个数组或者是map来保存对应字母出现的次数。在这,我用的是一维数组,用来保存每个字母出现的次数,所以数组的长度得是26,保证‘a~z’都能有位置存放。接着,在遍历s2数组的时候,我们维持一个大小为s1字符串长度大小的滑动窗口,规定每次从窗口的右边进入一个元素的时候,对应位置出现的元素出现的次数减1;当i的值大于等于s1的长度的时候,我们就要淘汰掉滑动窗口最左边的元素,将该位置的元素出现的次数加1。最后,我们每次都判断数组中的元素是否都为0,是的话就说明含有s1子串,否则就没有。

      为什么这样做是能行的呢?我们首先将s1中的每个字符出现的次数都记上,接着我们去匹配s2中的每个字符,之所以我们规定滑动窗口大小为s1,就是因为只要在滑动窗口中的每个字符能使整个数组为0,那么就说明含有此子串了啊!记住:不管遍历s1还是s2的时候,我们都操作的是count数组。以前也有一道题是和滑动窗口相关的:Contains Duplicate II .

代码:

主体部分:

Leetcode之Permutation in String 问题

判断所有元素是否为0:

Leetcode之Permutation in String 问题