Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently checking if a string contains a set of words

Tags:

java

Say I have a number of sets of words such as: (water, flour, eggs) and (beans, water, milk)

If a user enters a string that contains all those words in any order, a message is displayed. Such as "I have eggs water and some flour" -> "That makes a cake".

What is the most efficient way to accomplish this, assuming there may be a large number of word set and message combinations to check, for each string the user enters.

My initial idea is to use .contains:

for(each-word-set)
{
  i = word-set.length;
  for(each-word)
  {
    if(string.contains(word))
    {
       j++
    }
  }
  if(i == j)
  {
     //Yes this string contains all words.
  }
}

Is there a better method than this?

like image 648
Daniel Avatar asked Jul 05 '14 00:07

Daniel


1 Answers

My initial way: Using the space as a delimiter.

We can do the following.

Steps

Create a List. As follows

1) Use Java split function. To create array.

 List<String> list = new ArrayList<String>(Arrays.asList(string.split(" ")))`;

2) Create a Hash Map.

Map<String, String> hash = new HashMap<String, String>();    
for(i = 0 ; i < list.length(); i++)
{
   hash.put(list[i], list[i]);
}

Where the list[i] is going to be your key.

3) Retrieve matches.

Now when the user enters a word you are interested in, you can use the containsKey
command. For example

  if (hash.containsKey("flour") && hash.containsKey("water") && hash.containsKey("beans");

  println("Whatever you want");

The thing to note is creating a HashTable is useful for big data sets. Here is a link, you should see to see the benefits. Retrieving data from a Hash Table is O(1), so virtually instantaneous.

Hopefully that was helpful.

like image 137
SeahawksRdaBest Avatar answered Nov 15 '22 00:11

SeahawksRdaBest