1. 程式人生 > 實用技巧 >Permutation in String

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; } }