import java.util.HashMap; import java.util.Map; public class SubstringTemplate { public int findSubstring(String s) { Map<Character, Integer> map = new HashMap<>(); int counter = 0; // Check whether the substring is valid int begin = 0, end = 0; // Two pointers, one points to tail and one to head int d = 0; // The length of the substring // Initialize the hash map here for (char c : s.toCharArray()) { map.put(c, 0); } while (end < s.length()) { // Modify counter here if (map.containsKey(s.charAt(end)) && map.get(s.charAt(end))-- > 0) { counter--; } // Counter condition while (counter == 0) { // Update d here if finding minimum if (/* some condition */) { d = end - begin; } // Increase begin to make it invalid/valid again if (map.containsKey(s.charAt(begin)) && map.get(s.charAt(begin))++ == 0) { counter++; } begin++; } end++; // Update d here if finding maximum or minimum } return d; } }