Untitled
unknown
java
2 years ago
2.9 kB
11
Indexable
import java.util.*;
import java.util.regex.*;
import java.util.stream.Collectors;
class Result {
public static List<Integer> validateRequests(List<String> blacklisted_ips, List<String> requests) {
// Convert wildcard IPs to regex patterns
List<Pattern> patterns = blacklisted_ips.stream()
.map(ip -> ip.replace("*", ".*")) // Convert wildcard to regex
.map(Pattern::compile) // Compile to Pattern
.collect(Collectors.toList());
// LinkedHashMap to maintain the order of IPs and their valid request counts
Map<String, Integer> validRequestCounts = new LinkedHashMap<>();
// Initialize the result list with the same size as requests
List<Integer> results = new ArrayList<>(Collections.nCopies(requests.size(), 0));
for (int i = 0; i < requests.size(); i++) {
String requestIP = requests.get(i);
boolean isBlocked = false;
// Check against blacklisted IPs
for (Pattern pattern : patterns) {
if (pattern.matcher(requestIP).find()) {
isBlocked = true;
break;
}
}
// Check the rate limit only if the request is not blocked by the blacklist
if (!isBlocked) {
// If the IP is new or too old (not in the last 5 seconds), reset the count
validRequestCounts.putIfAbsent(requestIP, 0);
// Iterate over the entries and decrease the count for stale timestamps
validRequestCounts.entrySet().removeIf(entry -> i - entry.getValue() >= 5);
// Check the request count for the current IP
if (validRequestCounts.get(requestIP) >= 2) {
isBlocked = true; // Block if more than 2 requests in the last 5 seconds
} else {
// Increase the valid request count
validRequestCounts.merge(requestIP, 1, Integer::sum);
}
}
// Record the result for the current request
results.set(i, isBlocked ? 1 : 0);
}
return results;
}
}
public class Solution {
public static void main(String[] args) {
// Example usage of the validateRequests function
List<String> blacklisted_ips = Arrays.asList("*111.*", "123.*", "34.*");
List<String> requests = Arrays.asList("123.1.23.34", "121.1.23.34", "121.1.23.34", "34.1.23.34", "121.1.23.34", "12.1.23.34", "121.1.23.34");
// Call the validateRequests function with the example inputs
List<Integer> results = Result.validateRequests(blacklisted_ips, requests);
// Print the results
for (Integer result : results) {
System.out.println(result);
}
}
}
Editor is loading...
Leave a Comment