I have read a lot of ways to find a substring in a string. But in my case, I need to find a string of words (ie substring) inside a string. We can achieve this in O(n^3)
times which is a very bad time complexity
For example
sentences = ["jim likes mary", "kate likes tom", "tom does not like jim"]<br/>
phrases = ["jim tom", "likes"]
I want to find the complete phrase in the sentence irrespective of the position
In the above case, the output will be
[2, [0,1]]
Explanation: Wherever all words of phrase match in the sentence return the index of the sentence
1) The first phrase jim tom is only present in 2nd indexes of sentences which is tom does not like jim so return the 2nd index
2) Whereas the second phrase likes are present in 1st and 2nd array so return 0 and 1 indices
I did with brute force but that is not an efficient way to do it
final_arr = []
phrases.each do |phrase|
temp_arr = []
sentences.each_with_index do |sentence, index|
multiple_word_phrase = phrase.split(" ")
if multiple_word_phrase.length > 1
flag = 1
multiple_word_phrase.each do |word|
if !sentence.include?(word)
flag = 0
break
end
end
temp_arr << index if flag == 1
else
temp_arr << index if sentence.include?(phrase)
end
end
final_arr << temp_arr if temp_arr.any?
end
Is there any efficient way to achieve this problem O(NlogN) Time
. I think this can be achieved with dynamic programming but not sure how to do it