We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
publicstaticList<String>vanity(List<String>codes,List<String>numbers){//avoid duplicated inputSet<String>uniqueNumbers=newHashSet<>(numbers);Set<String>uniqueCodes=newHashSet<>(codes);// generate the keypadMap<Character,Integer>t9Keymap=newHashMap<>();charcharacter='A'-1;for(inti=2;i<10;i++){for(intj=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=newArrayList<>();uniqueCodes.forEach(code->{code=code.toUpperCase();StringBuildernumbersFromCodeBuilder=newStringBuilder();code.chars().forEach(c->numbersFromCodeBuilder.append(t9Keymap.get((char)c)));transformedCodes.add(numbersFromCodeBuilder.toString());});System.out.println(transformedCodes);//search the codes in the numbersListList<String>result=newArrayList<>();uniqueNumbers.forEach(number->transformedCodes.forEach(code->{if(number.contains(code)){result.add(number);}}));// sort and return the arrayresult.sort(String::compareTo);System.out.println(result);returnresult;}
static Map<Character, Integer> table; static Set<String> masterPhoneNums; public static List<String> vanity(List<String> codes, List<String> numbers) { table = initTable(); masterPhoneNums = new LinkedHashSet<>(); masterPhoneNums.addAll(numbers); List<String> resPhone = new ArrayList<String>(); String vanityCode; List subVanityNums; for(String code: codes){ vanityCode = vanityCode2Num( code ); subVanityNums = findVanityNum(vanityCode); if( subVanityNums.size()>0){ resPhone.addAll(subVanityNums); } System.out.println("code:"+code+ " subVanityNums:"+subVanityNums); subVanityNums.clear(); } Collections.sort(resPhone); return resPhone; } static List findVanityNum(String vanityNum){ List arrPhNum = new ArrayList(); System.out.println("total phone masterPhoneNums:"+masterPhoneNums.size()); int counter=0; for(String phNum: masterPhoneNums) { if(phNum.contains(vanityNum)){ arrPhNum.add(phNum); counter++; } } System.out.println("counter:"+counter); return arrPhNum; } static String vanityCode2Num(String vanityCode){ String vanityNum = ""; for(int i =0; i<vanityCode.length(); i++) { vanityNum += table.get(vanityCode.charAt(i)); } System.out.println("vanityCode:"+vanityCode + " vanityNum:"+vanityNum); return vanityNum; } static Map<Character, Integer> initTable() { Map<Character, Integer> table = new HashMap<Character, Integer>(); Character j='A'; for(int i=2;i<10;i++,j++) { table.put(j,i); table.put(++j,i); table.put(++j,i); if(i==7 || i==9) { table.put(++j,i); } } return table; } }