Vanity Number Search

  • + 0 comments
        public static List<String> vanity(List<String> codes, List<String> numbers) {
    		//avoid duplicated input
            Set<String> uniqueNumbers = new HashSet<>(numbers);
            Set<String> uniqueCodes = new HashSet<>(codes);
    
            // generate the keypad
    			Map<Character, Integer> t9Keymap = new HashMap<>();
            char character = 'A' - 1;
            for (int i = 2; i < 10; i++) {
                for (int j = 0; j < 3; j++) {
                    t9Keymap.put(++character, i);
                }
                if (i == 7 || i == 9) {
                    t9Keymap.put(++character, i);
                }
            }
            System.out.println(t9Keymap);
    
    
            //translate codes to "numbers"
            List<String> transformedCodes = new ArrayList<>();
            uniqueCodes.forEach(code -> {
                code = code.toUpperCase();
                StringBuilder numbersFromCodeBuilder = new StringBuilder();
                code.chars().forEach(c -> numbersFromCodeBuilder.append(t9Keymap.get((char) c)));
    
                transformedCodes.add(numbersFromCodeBuilder.toString());
    
            });
            System.out.println(transformedCodes);
    
    
            //search the codes in the numbersList
            List<String> result = new ArrayList<>();
            uniqueNumbers.forEach(number -> transformedCodes.forEach(code -> {
                        if (number.contains(code)) {
    
                            result.add(number);
                        }
                    })
            );
    
    
            // sort and return the array
            result.sort(String::compareTo);
            System.out.println(result);
    
            return result;
        }