LeetCode 438. Find All Anagrams in a String

Inequality-Sign發表於2018-03-19

Given a string s and a non-empty string p, find all the start indices of p’s anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

給出兩個字串s和p找出s中所有和p組成元素相同的子串起始下標
一開始用了暴力法,一個一個比較,果不其然超時了。
然後網上查了下,發現是用hash來做的。看了一下相關程式碼。豁然開朗,時間複雜度瞬間降為o(n)

char[256] hash來記錄p中的組成
left記錄視窗左端的index
right記錄視窗右端的index
count記錄剩餘未匹配的元素個數 這個count是時間複雜段降低的關鍵所在

 public List<Integer> findAnagrams(String s, String p) {

        List<Integer> list = new ArrayList<>();
        if(s.length() == 0 || p.length() ==0) return list;
        if(s.length() < p.length()) return list;
        int[] hash = new int[256];
        char[] pch = p.toCharArray();
        char[] sch = s.toCharArray();
        //記錄還未匹配的個數
        int count = 0;
        //將p對映到hash表中
        for (char ch : pch) {
            hash[ch]++;
            count++;
        }
        //視窗左右的index初始化
        int left = 0;
        int right = 0;

        while (right < sch.length) {
            //
            if(hash[sch[right]]-- > 0){
                count--;
            }
            if (count == 0) {
                list.add(left);
            }
            if (right - left  + 1!= p.length()) {
                right++;
            } else {
                if(hash[sch[left]]++ >= 0) count++;
                right++;
                left++;
            }
        }
        return list;



    }

雖然是個簡單題,但難度和含金量不亞於中等題。
這個題讓我對hash對映的理解更加深刻了,好題,贊一個!

相關文章