Skip to content

Commit

Permalink
feat: LC-0438: Find All Anagrams in a String
Browse files Browse the repository at this point in the history
add java solution for leetcode problem 438 - Find All Anagrams in a String
  • Loading branch information
galaumang committed Oct 7, 2023
1 parent dc2d804 commit 57c1e66
Showing 1 changed file with 48 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package dsalgo.string;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LC0438_FindAllAnagrams {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> ans = new ArrayList<>();
if (s == null || s.length() == 0 || s.length() < p.length()) {
return ans;
}

Map<Character, Integer> map = new HashMap<>();
for (char c : p.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}

// The number of distinct characters
int counter = map.size();
for (int left = 0, right = 0; right < s.length(); right++) {
char cRight = s.charAt(right);
if (map.containsKey(cRight)) {
map.put(cRight, map.get(cRight) - 1);
if (map.get(cRight) == 0) {
counter -= 1;
}
}

while (counter <= 0) {
char cLeft = s.charAt(left);
if (map.containsKey(cLeft)) {
map.put(cLeft, map.get(cLeft) + 1);
if (map.get(cLeft) > 0) {
counter += 1;
}
}
if (right - left + 1 == p.length()) {
ans.add(left);
}
left++;
}
}

return ans;
}
}

0 comments on commit 57c1e66

Please sign in to comment.