import java.util.*; public class Main { private static int maxRemovals(String currentString, List<String> substrings, Map<String, Integer> memo) { if (memo.containsKey(currentString)) { return memo.get(currentString); } int maxCount = 0; for (String substring : substrings) { int position = currentString.indexOf(substring); if (position != -1) { String newString = currentString.substring(0, position) + currentString.substring(position + substring.length()); maxCount = Math.max(maxCount, 1 + maxRemovals(newString, substrings, memo)); } } memo.put(currentString, maxCount); return maxCount; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int numSubstrings = sc.nextInt(); List<String> substrings = new ArrayList<>(); for (int i = 0; i < numSubstrings; i++) { substrings.add(sc.next()); } String mainString = sc.next(); Map<String, Integer> memo = new HashMap<>(); System.out.println(maxRemovals(mainString, substrings, memo)); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter