Advertisement
CR7CR7

hashset

Apr 11th, 2023
1,096
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.25 KB | None | 0 0
  1. import java.util.HashSet;
  2. import java.util.Scanner;
  3.  
  4. public class LicensePlates {
  5.  
  6.     public static void main(String[] args) {
  7.         // Create a scanner object to read input
  8.         Scanner scanner = new Scanner(System.in);
  9.  
  10.         // Read the allowed letters and split them by comma
  11.         String[] allowedLetters = scanner.nextLine().split(",");
  12.  
  13.         // Create a hash set to store the allowed letters for faster lookup
  14.         HashSet<Character> allowedSet = new HashSet<>();
  15.  
  16.         // Loop through the allowed letters and add them to the hash set
  17.         for (String letter : allowedLetters) {
  18.             allowedSet.add(letter.charAt(0));
  19.         }
  20.  
  21.         // Read the number of license plates N
  22.         int N = scanner.nextInt();
  23.  
  24.         // Consume the remaining newline
  25.         scanner.nextLine();
  26.  
  27.         // Loop through the license plates
  28.         for (int i = 0; i < N; i++) {
  29.             // Read the next license plate
  30.             String plate = scanner.nextLine();
  31.  
  32.             // Check if the license plate is valid
  33.             if (isValid(plate, allowedSet)) {
  34.                 // Print the license plate
  35.                 System.out.println(plate);
  36.             }
  37.         }
  38.  
  39.         // Close the scanner
  40.         scanner.close();
  41.     }
  42.  
  43.     // A helper method to check if a license plate is valid
  44.     public static boolean isValid(String plate, HashSet<Character> allowedSet) {
  45.         // Check if the plate has 8 characters
  46.         if (plate.length() != 8) {
  47.             return false;
  48.         }
  49.  
  50.         // Check if the first and second characters are in the allowed set
  51.         if (!allowedSet.contains(plate.charAt(0)) || !allowedSet.contains(plate.charAt(1))) {
  52.             return false;
  53.         }
  54.  
  55.         // Check if the third, fourth, fifth and sixth characters are digits
  56.         for (int i = 2; i <= 5; i++) {
  57.             if (!Character.isDigit(plate.charAt(i))) {
  58.                 return false;
  59.             }
  60.         }
  61.  
  62.         // Check if the seventh and eighth characters are in the allowed set
  63.         if (!allowedSet.contains(plate.charAt(6)) || !allowedSet.contains(plate.charAt(7))) {
  64.             return false;
  65.         }
  66.  
  67.         // If all checks pass, return true
  68.         return true;
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement