如果它包含特定字符串,我正在创建一个过滤二维字符串数组的搜索。用户可以在拨打与拨号盘对应的号码(0-9)时进行搜索。例如,如果键入数字56,搜索将查找包含'56','JJ','JM',JO','KM','KN','KO','LM'的任何字符串序列, 2-D阵列中的'LN','LO'。
我的方法是将可能性存储在数组中,然后遍历2-D数组以查看它们中是否包含序列;嵌套循环。我想知道在我花几个小时写这篇文章之前,是否有更好的方法可以做到这一点或链接到类似的东西。
答案 0 :(得分:1)
一种方法是(如果必须是一个数组)根据输入的字母构建可能名称的子集,并在输入每个字母后比较子集而不是整个集合。
例如,如果您以
开头Bill, Bob, Conroy, Fran, Riley, Shelley
输入2(A,B,C)后,您将被遗忘
Bill, Bob, Conroy, (Fran if contains)
然后在输入6(M,N,O)后,您将被留下
Bob, Conroy, (Fran if contains)
如果以开头 为了做到这一点,你需要一组目前已经匹配的索引,List可能是最好的实现
List<Integer> indicesMatched;
如果包含 您需要存储匹配字符串的索引以及第一个匹配字母在字符串中的索引,可能是地图(或列表并误用Point类)
Map<Integer, Integer> matched; // where the key is the array index and the value is the string index
然后你可以用第一组匹配的索引来填充它。然后当你比较第二个数字/字母时,只使用列表中存储的那些索引,并删除那些与第二个字母不匹配的索引
伪代码:(用于开头)
// First key press
// For each entry in your array
// If a match
// Add to matched index List
// Second Key Press -- Repeat this step for each subsequent key press
// For each index in list
// Get the entry at that index
// If not a match in second letter
// Remove the index from list
伪代码:(对于contians)
// First key press
// For each entry in your array
// If a match
// Add to matched index map
// Second Key Press -- Repeat this step for each subsequent key press
// For each index in map
// Get the entry at that index
// If not a match in second letter (based on the stored string index)
// Remove the index from map
答案 1 :(得分:0)
如果你有一个包含所有搜索过的字符串的数组(名字,我猜是在这种情况下),那么我会这样写:
考虑这个案例:
Adam
James
Kevin
Laurie
Lisa
Steve
用户输入5,我们循环确定:
start = 1; //index of "James"
end = 4; //index of "Lisa"
所以我们的阵列是
James
Kevin
Laurie
Lisa
现在用户输入了另一个数字,我们再次使用它(更小,给定一个完整的地址簿)数组,但这次比较每个名称中的第二个字母,消除了不符合可能性的索引。所以,再次,如果用户现在输入2,这意味着可能的字母是A,B和C.数组再次被击倒:
James
Laurie
等等。