Find All Anagrams in a String


  • 0
    S
    class Solution {
        public List<Integer> findAnagrams(String s, String p) {
        List<Integer> indexes = new ArrayList<>();
    
    		if (s == null || s.length() == 0) {
    			return indexes;
    		}
    
    		if (p.length() > s.length()) {
    			return indexes;
    		}
    
    		Map<Character, Integer> characterCountMap = new HashMap<>();
    		for (int j = 0; j < p.length(); j++) {
    			char c = p.charAt(j);
    			if (characterCountMap.containsKey(c)) {
    				characterCountMap.put(c, characterCountMap.get(c) + 1);
    			} else {
    				characterCountMap.put(c, 1);
    			}
    		}
    
    		int chracterMatch = 0;
    		for (int i = 0; i < s.length(); i++) {
    			char c = s.charAt(i);
    			if (characterCountMap.containsKey(c)) {
    				characterCountMap.put(c, characterCountMap.get(c) - 1);
    				if (characterCountMap.get(c) == 0) {
    					chracterMatch++;
    				}
    			}
    			if (i >= p.length()) {
    				c = s.charAt(i - p.length());
    				if (characterCountMap.containsKey(c)) {
    					characterCountMap.put(c, characterCountMap.get(c) + 1);
    					if (characterCountMap.get(c) == 1) {
    						chracterMatch--;
    					}
    				}
    			}
    			if (chracterMatch == characterCountMap.size()) {
    				indexes.add(i - p.length() + 1);
    			}
    		}
    		return indexes;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.