-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: LC-0438: Find All Anagrams in a String
add java solution for leetcode problem 438 - Find All Anagrams in a String
- Loading branch information
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
48 changes: 48 additions & 0 deletions
48
solutions-java/src/main/java/dsalgo/string/LC0438_FindAllAnagrams.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |