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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutation-in-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

截取一段子字符串,然后与目标字符串比较,如果把目标字符串打乱重拍的话,那样就太烦了,效率肉眼可见的低。其实不妨想想,子字符串与目标字符串任一排列相同即可,说明我们只需要统计各字符的个数,如果各字符的个数都相等的话,那么肯定会有一种排列是符合要求的。这样一来,我们就只需统计字符串的个数并且比较,而不需要做一次全排列组合了。这样可以大幅度降低程序执行的时间。

class Solution {
    public boolean checkInclusion(String s1, String s2) {
        int[] counts1 = new int[26];
        int len = s1.length();
        for(int i = 0; i < len; i++){
            counts1[s1.charAt(i) - 'a']++;
        }
        for(int j = 0; j <= s2.length() - len ; j++) {
            String str = s2.substring(j, j+len);
            if(count(str, counts1))
                return true;
        }
        return false;
    }

    public static boolean count(String str, int[] counts) {
        int[] counts2 = new int[26];
        for(int i = 0; i < str.length(); i++) {
            counts2[str.charAt(i) - 'a']++;
        }
        for(int k = 0; k < 26; k++) {
            if(counts[k] != counts2[k])
                return false;
        }
        return true;
    }
}
原文地址:https://www.cnblogs.com/WakingShaw/p/13637488.html