Interview 150
Find All Anagrams in a String
- Problem
- LC 438
- File
- interview150_LC438FindAllAnagramsInAString.java
- Path
- pkg5leetcode/interview150/interview150_LC438FindAllAnagramsInAString.java
- Package
- pkg5leetcode.interview150
- Command
- java pkg5leetcode/interview150/interview150_LC438FindAllAnagramsInAString.java
- Approach
- Sliding window with char frequency match count.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.interview150;2 3/*4 * Find All Anagrams in a String | LC 4385 * APPROACH: Sliding window with char frequency match count.6 * COMPLEXITY: Time O(n), Space O(1)7 */8import java.util.*;9 10public class interview150_LC438FindAllAnagramsInAString {11 static List<Integer> findAnagrams(String s, String p) {12 List<Integer> res = new ArrayList<>();13 if (p.length() > s.length()) return res;14 int[] need = new int[26], have = new int[26];15 for (char c : p.toCharArray()) need[c - 'a']++;16 for (int i = 0; i < s.length(); i++) {17 have[s.charAt(i) - 'a']++;18 if (i >= p.length()) have[s.charAt(i - p.length()) - 'a']--;19 if (i >= p.length() - 1 && Arrays.equals(need, have)) res.add(i - p.length() + 1);20 }21 return res;22 }23 24 public static void main(String[] args) {25 check(findAnagrams("cbaebabacd", "abc").equals(Arrays.asList(0, 6)), "case1");26 check(findAnagrams("abab", "ab").equals(Arrays.asList(0, 1, 2)), "case2");27 System.out.println("all tests passed");28 }29 30 static void check(boolean cond, String name) {31 if (!cond) throw new AssertionError("FAILED: " + name);32 System.out.println(" PASS " + name);33 }34}