joh*_*nes 30
所有呈现的解决方案具有O(n)的时间复杂度.为简单起见,我String#include?
用来检查这个词.这可以通过表单中的正则表达式来完成string=~ regex
.
File.read(filename).include?(word)
Run Code Online (Sandbox Code Playgroud)
如果您的文件非常大,这不是最佳解决方案,因为您将完整的文件读入内存并在之后开始搜索.你的记忆复杂度是O(n)
File.open(filename) do |f|
f.any? do |line|
line.include?(word)
end
end
Run Code Online (Sandbox Code Playgroud)
如果你的文件非常大,但是你知道你的行是一个常量值的上限,你现在的内存复杂度为O(1).
File.open(filename) do |f|
tmp= f.read(1024)
next true if tmp.include?(word)
until f.eof?
tmp= tmp[(-1*word.size)..-1] + f.read(1024)
next true if tmp.include?(word)
end
next false
end
Run Code Online (Sandbox Code Playgroud)
在此变体中,我们从文件中读取等大小的块.所以无论文件的条件是什么,我们的内存复杂度都是O(1)
File.readlines(file).each {|l| l.grep(/#{exp_search}/).each {|r| puts file + ' : ' + r}}
Run Code Online (Sandbox Code Playgroud)