我正在创建一个搜索来过滤包含特定字符串的二维字符串数组。用户可以在调用与拨号盘(0-9)对应的号码时进行搜索。例如,如果键入数字 56,搜索将查找包含 '56'、'JJ'、'JM'、JO'、'KM'、'KN'、'KO'、'LM'、二维数组中的“LN”、“LO”。
我的方法是将可能性存储在一个数组中,然后循环遍历二维数组以查看是否有任何可能性包含该序列;嵌套循环。在我花几个小时编写它之前,我想知道是否有更好的方法来执行此操作或指向类似内容的链接。
最佳答案
一种方法是(如果它必须是数组)根据输入的字母构建可能名称的子集,并在输入每个字母后比较子集而不是完整集。
例如,如果您开始于
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<Integer> indicesMatched;
如果包含 您需要存储匹配字符串的索引以及字符串中第一个匹配字母所在位置的索引,可能作为映射(或 List 并误用 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
关于java - 字母数字拨号盘搜索 - Java/Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17476955/