有一个表格,如下所示:
Code(starts with) Value
1 AAA
101D BBB
101DG CCC
2 DDD
上表包含列代码和相应的值。代码列表示字符串以给定的代码开头,在将其与用户的输入代码进行比较时,将从表的值列中分配相应的值。
例如:
- 如果用户的代码是 100000,那么值应该是 AAA......
- 对于用户的代码 101D1111,值应该是 BBB(即使以 1 开头也不是 AAA,因为我们将考虑与 101D 进行更重要的比较)......
- 对于用户的代码为 101DG222,值应该是 CCC(即使它以 101D 开头也不是 BBB,因为我们会注意到最重要的比较).....
- 对于用户 cose 23333,值 = DDD.....
我将下表放在一个哈希表中,键作为代码列,值作为值列。
HashTable hash= new HashTable();
hash.put("1","AAA");
hash.put("101D","BBB");
hash.put("101DG","CCC");
hash.put("2","DDD");
String comp="101D1111";//string to compare
Iterator itr= hash.entrySet().iterator();
while(itr.hasNext())
{
Map.Entry e=(Map.Entry)itr.next();
String key= (String).getKey();
//**Here logic is needed to compare comp and key and retrieve the corrsponding value here as BBB**
}
请帮助我解决这个逻辑。
您必须首先按键长度对条目进行排序,最长的在前,最短的在最后。因为你首先要检查你的代码是否以101DG
开头,然后才检查它是否以101DG
开头,最后以1
开头。
然后要检查匹配项,您可以使用如下所示的内容:
if (comp.substring(0,key.length()).equals(key)) {
// it's a match — use this Value
}
我认为HashTable
不是用于此目的的良好数据结构,因为如果您要遍历所有条目,那么HashTable
有什么意义?
更好的结构(不过需要更多的工作来实现)是一棵树。树的每个节点将代表一个前缀和与之关联的值:
例如,这是树在示例中的外观:
ROOT
/
1 (AAA) 2 (DDD)
|
10
|
101
/
101D (BBB)
|
101DG (CCC)
现在,对于给定的用户代码,您开始从 ROOT 遍历树,每次都跟随保存用户代码下一个字符的子节点。当找不到任何匹配的子节点时,将停止。您访问的每个节点,您都会获取存储在其中的值。返回找到的最后一个值。
如果您仍然不精通存在的复杂数据结构,那么这个简单的解决方案将为您提供帮助
String keySearch=new String();
String val=null;
for(i=0;i<comp.length();i++){
keySearch+=comp.charAt(i);
if(table.contains(keySearch)){
val=map.get(keySearch);
}
else
break;
}
但在这种情况下使用哈希表并不是真正有效
代码就可以了。您还可以在迭代器中使用泛型来确保代码类型安全。
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
public class TestClass {
public static void main(String[] args) {
HashMap hash= new HashMap<String, String>();
hash.put("1","AAA");
hash.put("101D","BBB");
hash.put("101DG","CCC");
hash.put("2","DDD");
String comp="101D1111";//string to compare
Iterator itr= hash.entrySet().iterator();
String value = null;
int length = 0;
while(itr.hasNext())
{
Map.Entry e=(Map.Entry)itr.next();
if(comp.startsWith(((String)e.getKey())) && ((String)e.getKey()).length() > length) {
value = (String)e.getValue();
length = ((String)e.getKey()).length();
}
//**Here logic is needed to compare comp and key and retrieve the corrsponding value here as BBB**
}
System.out.println(value);
}
}