有效地检查字符串是否包含一组单词



假设我有若干组单词,如:(水,面粉,鸡蛋)和(豆子,水,牛奶)

如果用户输入的字符串包含所有这些字的任意顺序,则显示一条消息。例如"我有鸡蛋,水和一些面粉" -> "那是做蛋糕的"。

假设对于用户输入的每个字符串,可能有大量的单词集和消息组合需要检查,那么最有效的方法是什么呢?

我最初的想法是使用。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.
  }
}

还有比这更好的方法吗?

我最初的方法:使用空格作为分隔符。

我们可以做以下事情。

步骤

创建列表。如下

1)使用Java拆分函数。创建数组

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

2)创建一个Hash Map

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

其中list[i]将成为你的钥匙。

3)检索匹配项。

现在,当用户输入您感兴趣的单词时,您可以使用containsKey
命令。例如

  if (hash.containsKey("flour") && hash.containsKey("water") && hash.containsKey("beans");
  println("Whatever you want");

需要注意的是,创建HashTable对于大数据集很有用。这里有一个链接,你应该看到的好处。从哈希表中检索数据是O(1),因此几乎是瞬间的。

希望这对你有帮助。

扩展我的评论。还有一些错误。到目前为止,我的最终解决方案是:

public class Someclass {
    public static void main(String[] args) {
        String[] words = { "water", "flour", "eggs", "beans", "water", "milk" };
        String[] testStrings = { "water flour eggs beans water milk", "somewhat else",
                        "wader flour ekks beans water milk" };
        for (String string : testStrings) {
            boolean found = true;
            for (String word : words) {
                if (!string.contains(word)) {
                    found = false;
                    break;
                }
            }
            if (found) {
                System.out.println(string + " - That makes a cake");
            } else {
                System.out.println(string + " - That makes no cake");
            }
        }
    }
}
You can first create an array or list of strings splitted by space as:
List<string>userStr= userEntry.split(" ");
Now use extended for loop within another loop as:
for(String s: userStr)
{
    for(String d: yourList){
       if(s.equals d){
          //your code 
           break;
        }
     }
}

最新更新