A different way of solving based on KMP

  • 0

    The idea with mine is slightly influenced by KMP. We match counts until the matched length equals the length of s1. If we encounter a mismatch of characters, we use two pointers to find a new offset for the matching while recalculating the counts.

    public class Solution {
        public boolean checkInclusion(String s1, String s2) {
            int len = 0;
            char[] arr = s2.toCharArray();
            int[] counts = new int[26];
            for (char c : s1.toCharArray())
            for (int i = 0; i < arr.length; i++) {
                if (counts[arr[i]-'a'] > 0) {
                    if (++len==s1.length())
                        return true;
                } else if (len > 0) {
                    int j = i-len;
                    while (arr[i] != arr[j]) {
            return false;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.