educative.io

Educative

Is the following would be an acceptable solution?

public static List<Integer> findStringAnagrams(String str, String pattern) {
    List<Integer> resultIndices = new ArrayList<Integer>();
    
    if(str == null || pattern == null || str.isEmpty() || pattern.isEmpty()) {
      return resultIndices;
    }

    int start = 0;
    int end = 0;
    int count = 0;
    Map<Character, Integer> pMap = new HashMap<>();
    for(Character ch : pattern.toCharArray()) {
      pMap.put(ch, pMap.getOrDefault(ch, 0) + 1);
    }

    while(start <= end && end < str.length()) {

      Character ch = str.charAt(end);
      if(pMap.containsKey(ch) && pMap.get(ch) > 0) {
        pMap.put(ch, pMap.get(ch) - 1);
        count++;
        end++;
      }
      else if(!pMap.containsKey(ch)) {
        count = 0;
        while(start < end) {
          pMap.put(str.charAt(start), pMap.get(str.charAt(start)) + 1);
          start++;
        }
      }
      // pMap.get(ch) == 0
      else {
        pMap.put(str.charAt(start), pMap.get(str.charAt(start)) + 1);
        count--;
        start++;
      }

      if(count == pattern.length()) {
        resultIndices.add(start);
      }      
    }

    return resultIndices;
  }

Type your question above this line.

Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/6005911854252032