我正在为我的服务在Java中搜索一种模式或编程技术。
服务的输入是字符串数组。这些字符串表示一个文件和一些信息。
服务的输出是精确字符串的Map和布尔值。布尔值表示该信息存在于文件中。
例如输入
["file1/dog","file2/cat","file1/rabbit"]输出
{"file1/dog":"false","file2/cat":"true","file1/rabbit":"true"}我只想打开一次文件,并搜索该文件中的所有信息。打开文件一,搜索狗和兔子。
如何在Java中快速做到这一点?
我应该使用带文件的Map作为收集信息的密钥吗?例如:
{"file1": ["dog","rabbit"], "file2": ["cat"]}下一步是遍历键以检查每个文件。
发布于 2022-11-23 14:51:47
为了有效地解决这个问题,必须考虑到系统的假设和先决条件。
假设文件大小很小
如果每个文件都相对较小,那么我建议缓存文件的内容。
当搜索模式不可预测时
如果您不能预测可能的搜索条件,或者文件的内容不能分割成可搜索的项,那么只需使用String#contains检查缓存的文件内容就可以了。
但是,如果搜索条件是可预测的,或者文件包含一定数量的搜索词,那么您可以尝试使用下面讨论的方法对这些术语进行索引(每个方法都有不同的计算要求)。
O(m)时间复杂度方法--其中m是文件数
假设每个搜索项都是文件中的一个单词,最好将文件内容存储为HashSet (利用HashSet#contains的O(1)时间复杂性),每个元素都是一个单词或潜在的搜索项。
这样,您就可以拥有这样一个Map:
//the following code runs once at startup
//map containing file names against their words as a HashSet
Map<String, HashSet<String>> fileContents = new HashMap<>();
//add files to Map (assuming parseFileContents returns a HashSet<String>)
fileContents.put("file1", parseFileContents("file1"));
fileContents.put("file2", parseFileContents("file2"));
fileContents.put("file3", parseFileContents("file3"));
//the following code runs every time a request is made
//get files containing the word "dog" (time complexity is O(m) where m is the number of files)
fileContents.entrySet()
.stream()
.filter(e -> e.getValue().contains("dog"))
.map(Map.Entry::getKey)
.collect(LinkedList::new);O(1)时间复杂度方法
如果搜索模式是可预测的,而且并不多,那么您可以创建一个Map,其中搜索词是键,文件的List是值:
//the following code runs once at startup
//map containing possible search patterns against files that they appear in
Map<String, List<String>> patternsAgainstFiles = new HashMap<>();
//then loop through all files and each term found in the file as a key to the map,
//with the file being added to the list in the value
//the following code runs every time a request is made
//get files containing the word "dog" (time complexity is O(1) after initial computation at startup)
patternsAgainstFiles.getOrDefault("dog", new LinkedList<>());其他选择
在下列情况下使用此选项:
期间发生更改。
在这种情况下,您别无选择,只有每次想在文件中搜索给定的模式时,都要在辅助存储中实际搜索该文件。
在编写本报告时,我可以想到的最佳方法是为每个文件打开一个FileInputStream (或类似的内容),然后每次读取一个字节,并将其附加到“当前缓冲区”中,该缓冲区的长度永远不会超过搜索项的字节长度。每当“当前缓冲区”具有与搜索项相同的长度(以字节为单位)时,将根据搜索项对其进行计算,如果它们匹配,则搜索项在文件中,但如果它们不匹配,则弹出“当前缓冲区”中的第一个字节并继续。
以上是我的所有建议,也许有更有效的方法来完成手头的任务。这些都是我能想到的最好的写作方法。
https://stackoverflow.com/questions/74547899
复制相似问题