FindKeywords
package com.person; import java.util.HashMap; import java.util.Map; public class FindKeywords { public int getSubString(String s, String[] keywords) { Map<String, Integer> keywordMap = new HashMap<>(); Map<String, Integer> stMap = new HashMap<>(); for (String key: keywords) { keywordMap.put(key, keywordMap.getOrDefault(key, 0)+1); } String[] st = s.split("\\s+"); int i=0, j=0; int minCount = Integer.MAX_VALUE; while (i<st.length && j<st.length) { if (keywordMap.containsKey(st[j])) { stMap.put(st[j], stMap.getOrDefault(st[j], 0) + 1); } j++; while (i<j && doMapsMatch(stMap, keywordMap)) { minCount = Math.min(minCount, j - i); if (stMap.containsKey(st[i])) { int stCount = stMap.get(st[i]); stCount -= 1; if (stCount == 0) { stMap.remove(st[i]); } else { stMap.put(st[i], stCount); } } i++; } } return minCount; } private static boolean doMapsMatch(Map<String, Integer> mp1, Map<String, Integer> mp2) { if (mp1.size() != mp2.size()) { return false; } for (Map.Entry<String, Integer> entry: mp1.entrySet()) { if (!mp2.containsKey(entry.getKey()) || ( mp2.containsKey(entry.getKey()) && !mp2.get(entry.getKey()).equals(entry.getValue()))) { return false; } } return true; } public static void main(String[] args) { String s = "Hey green hero why apple end apple cat blow hello apple apple cat blow"; String[] keywords = new String[]{"apple", "apple", "cat", "blow"}; FindKeywords ob = new FindKeywords(); int ans = ob.getSubString(s, keywords); System.out.println(ans); } }
Leave a Comment