Untitled
import java.util.*; import java.util.regex.*; public class IPValidator { public static List<Integer> validateRequests(List<String> blacklistedIps, List<String> requests) { List<Integer> results = new ArrayList<>(); Map<String, Queue<Integer>> requestTimes = new HashMap<>(); for (String req : requests) { boolean isBlocked = false; for (String bip : blacklistedIps) { if (ipMatches(req, bip)) { // Check for the number of allowed requests in the last 5 seconds Queue<Integer> times = requestTimes.getOrDefault(req, new LinkedList<>()); while (!times.isEmpty() && times.peek() <= Integer.parseInt(req.split(",")[0]) - 5) { times.poll(); } if (times.size() >= 2) { isBlocked = true; } times.offer(Integer.parseInt(req.split(",")[0])); requestTimes.put(req.split(",")[1], times); break; } } results.add(isBlocked ? 1 : 0); } return results; } private static boolean ipMatches(String request, String blacklistedIp) { String[] reqParts = request.split(",")[1].split("\\."); String[] bipParts = blacklistedIp.split("\\."); for (int i = 0; i < bipParts.length; i++) { if (!bipParts[i].equals("*") && !bipParts[i].equals(reqParts[i])) { return false; } } return true; } public static void main(String[] args) { List<String> blacklistedIps = Arrays.asList("111.*.255", "12.*"); List<String> requests = Arrays.asList("1,121.3.5.255", "2,12.13.5.255", "3,111.3.5.255", "4,121.3.5.255"); List<Integer> results = validateRequests(blacklistedIps, requests); for (int result : results) { System.out.println(result); } } }
Leave a Comment