使用TreeMap
和floorEntry(K key)
方法:
返回與最大鍵小於或等於給定的密鑰,或null
關聯的鍵 - 值映射如果不存在這樣的密鑰。
以下簡化。真實代碼需要搜索是否找到無效條目,例如如果地圖有一個鍵0060175551000
,在這種情況下,您需要在搜索鍵和找到的鍵之間找到公共前綴,然後再次執行查找。沖洗並重復。
TreeMap<String, String> map = new TreeMap<>();
map.put("0060175559138", "VIP");
map.put("006017555" , "National");
map.put("006017" , "Local");
map.put("0060" , "X");
String key = "0060175552020";
Entry<String, String> entry = map.floorEntry(key);
if (entry == null)
System.out.println("Not found: " + key);
else {
System.out.println(key);
System.out.println(entry);
}
輸出
0060175552020
006017555=National
UPDATE有完整的代碼,具有用於循環擴展搜索。
private static Entry<String, String> lookup(NavigableMap<String, String> map, String key) {
String keyToFind = key;
for (;;) {
Entry<String, String> entry = map.floorEntry(keyToFind);
if (entry == null)
return null;
String foundKey = entry.getKey();
int prefixLen = 0;
while (prefixLen < keyToFind.length() && prefixLen < foundKey.length() &&
keyToFind.charAt(prefixLen) == foundKey.charAt(prefixLen))
prefixLen++;
if (prefixLen == 0)
return null;
if (prefixLen == foundKey.length())
return entry;
keyToFind = key.substring(0, prefixLen);
}
}
測試
TreeMap<String, String> map = new TreeMap<>();
map.put("0060175559138", "VIP");
map.put("0060175551000", "Other");
map.put("006017555" , "National");
map.put("006017" , "Local");
map.put("0060" , "X");
System.out.println(lookup(map, "0060175559138"));
System.out.println(lookup(map, "0060175552020"));
System.out.println(lookup(map, "0055708570068"));
System.out.println(lookup(map, "8684064893870"));
輸出
0060175559138=VIP
006017555=National
null
null
你可能會考慮使用這個https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm – Vihar
也有人建議Trie。會看看他們兩個。謝謝 – spakai