判断s1字符串的全排列是否包含在s2中 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.

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].

解决:

①  给定两个字符串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;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1605403

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值