Created
May 24, 2020 12:57
-
-
Save Desolve/4f0f9cb395c0e50c50c1e8c1663c3669 to your computer and use it in GitHub Desktop.
0438 Find All Anagrams in a String
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
class Solution { | |
public List<Integer> findAnagrams(String s, String p) { | |
List<Integer> list = new ArrayList<>(); | |
if (s == null || s.length() == 0 || p == null || p.length() == 0 || s.length() < p.length()) return list; | |
int[] hash = new int[26]; | |
for (char c : p.toCharArray()) { | |
hash[c - 'a']++; | |
} | |
int left = 0, right = 0, count = p.length(); | |
while (right < s.length()) { | |
if (hash[s.charAt(right++) - 'a']-- >= 1) count--; | |
if (count == 0) list.add(left); | |
if (right - left == p.length() && hash[s.charAt(left++) - 'a']++ >= 0) count++; | |
} | |
return list; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment