Tries: Contacts

  • + 1 comment

    import java.io.; import java.math.; import java.security.; import java.text.; import java.util.; import java.util.concurrent.; import java.util.regex.*;

    public class Solution {

    private static final Scanner scanner = new Scanner(System.in);
    
    private static ArrayList<HashSet<String>> InitializeContactArray(){
    
        ArrayList<HashSet<String>> contactArray = new ArrayList<HashSet<String>>();
    
        for(int i=0;i<26;i++){
            contactArray.add(new HashSet<String>());
        }
    
        return contactArray;
    }
    
    private static int GetFirstCharacterIndex(String contact){
        return contact.charAt(0) - 97;
    }
    
    public static void main(String[] args) {
        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
    
        ArrayList<HashSet<String>> contactArray = InitializeContactArray();
    
        for (int nItr = 0; nItr < n; nItr++) {
            String[] opContact = scanner.nextLine().split(" ");
    
            String operation = opContact[0];
            String contact = opContact[1];
            Integer index = GetFirstCharacterIndex(contact);
            HashSet<String> contactSet = contactArray.get(index);
    
            if(operation.equals("add")){
                contactSet.add(contact);
            }
            else{
    
                Integer matches = 0;
    
                for (String contactName : contactSet) {
                    if(contactName.startsWith(contact)){
                        matches++;
                    }
                }
    
                System.out.println(matches);
            }
    
        }
    
        scanner.close();
    }
    

    }