Method: Algorithms::Search.kmp_search
- Defined in:
- lib/algorithms/search.rb
.kmp_search(string, substring) ⇒ Object
Knuth-Morris-Pratt Algorithm substring search algorithm: Efficiently finds the starting position of a substring in a string. The algorithm calculates the best position to resume searching from if a failure occurs.
The method returns the index of the starting position in the string where the substring is found. If there is no match, nil is returned.
Complexity: O(n + k), where n is the length of the string and k is the length of the substring.
Algorithms::Search.kmp_search("ABC ABCDAB ABCDABCDABDE", "ABCDABD") #=> 15
Algorithms::Search.kmp_search("ABC ABCDAB ABCDABCDABDE", "ABCDEF") #=> nil
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/algorithms/search.rb', line 43 def self.kmp_search(string, substring) return nil if string.nil? or substring.nil? # create failure function table pos = 2 cnd = 0 failure_table = [-1, 0] while pos < substring.length if substring[pos - 1] == substring[cnd] failure_table[pos] = cnd + 1 pos += 1 cnd += 1 elsif cnd > 0 cnd = failure_table[cnd] else failure_table[pos] = 0 pos += 1 end end m = i = 0 while m + i < string.length if substring[i] == string[m + i] i += 1 return m if i == substring.length else m = m + i - failure_table[i] i = failure_table[i] if i > 0 end end return nil end |