classSolution{ publicbooleancheckInclusion(String s1, String s2){ Map<Character, Integer> need = new HashMap<>(); Map<Character, Integer> window = new HashMap<>(); for (int i = 0; i < s1.length(); i++) { need.merge(s1.charAt(i), 1, (oldVal, newVal) -> ++oldVal); }
int left = 0, right = 0, valid = 0; while (right < s2.length()) { char r = s2.charAt(right); right++; if (need.containsKey(r)) { window.merge(r, 1, (oldVal, newVal) -> ++oldVal); if (window.get(r).equals(need.get(r))) { valid++; } }
while (right - left == s1.length()) { if (valid == need.size()) { returntrue; } char l = s2.charAt(left); left++; if (need.containsKey(l)) { if (window.get(l).equals(need.get(l))) { valid--; } window.compute(l, (k, v) -> --v); } } } returnfalse; } }