567. Permutation in Strin

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经过各种排列后是否是数的子串,程序如下:

class Solution {
    public boolean checkInclusion(String s1, String s2) {
        int len1 = s1.length(), len2 = s2.length();
        if (len1 > len2){
            return false;
        }
        char[] ch1 = new char[26];
        for (int i = 0; i < len1; ++ i){
            ch1[s1.charAt(i) - 'a'] ++;
        }
        int i = 0;
        while (i < len2){
            if (ch1[s2.charAt(i) - 'a'] > 0){
                char[] ch2 = new char[26];
                int c;
                for (int j = i; j < len2; ++ j){
                    c = s2.charAt(j) - 'a';
                    ch2[c] ++;
                    if (ch2[c] > ch1[c]){
                        if (ch1[c] == 0){
                            i = j;
                        }
                        break;
                    }
                    if (j - i + 1 ==  len1){
                        return true;
                    }
                }
            }
            i ++;
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/excellentlizhensbfhw/article/details/81810379