GuilinDev

Lc0438

05 August 2008

438 Find All Anagrams in a String

一个字符串中找到所有异位词子串的起始位置 - 滑动窗口 + HashMap/Array (模板集合,最后一个)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
    public List<Integer> findAnagrams(String s, String t) {
        List<Integer> result = new LinkedList<>();
        if (t.length() > s.length()) {
            return result;
        }
        Map<Character, Integer> map = new HashMap<>();
        for (char c : t.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        int counter = map.size();

        int begin = 0, end = 0;
//        int head = 0;
//        int len = Integer.MAX_VALUE;


        while (end < s.length()) {
            char c = s.charAt(end);
            if (map.containsKey(c)) {
                map.put(c, map.get(c) - 1);
                if (map.get(c) == 0) {
                    counter--;
                }
            }
            end++;

            while (counter == 0) {
                char tempc = s.charAt(begin);
                if (map.containsKey(tempc)) {
                    map.put(tempc, map.get(tempc) + 1);
                    if (map.get(tempc) > 0) {
                        counter++;
                    }
                }
                if (end - begin == t.length()) {
                    result.add(begin);
                }
                begin++;
            }

        }
        return result;
    }
}

比较直接的每个字串检查,也能过,时间复杂度lenS * lenP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        if (s.isEmpty()) {
            return result;
        }
        int lenS = s.length();
        int lenP = p.length();
        for (int i = 0; i < lenS - lenP + 1; i++) {
            String temp = s.substring(i, i + lenP);
            if (check(temp, p)) {
                result.add(i);
            }
        }
        return result;
    }
    private boolean check(String s1, String s2) {
        int[] arr = new int[26];
        int len = s1.length();
        for (int i =0 ; i < len; i++) {
            arr[s1.charAt(i) - 'a']++;
            arr[s2.charAt(i) - 'a']--;
        }
        for (int ch : arr) {
            if (ch != 0) {
                return false;
            }
        }
        return true;
    }
}