gpt4 book ai didi

java - 如何找到至少一次包含所有给定字符的单词

转载 作者:行者123 更新时间:2023-12-02 00:23:13 24 4
gpt4 key购买 nike

我正在使用此代码

                   while((dictionaryWord = br_.readLine()) != null) 
{
if(dictionaryWord.matches("^"+word.replace("*" , "." )+"$"))
{
incrementCounter();
System.out.println(dictionaryWord);
}
}

期望目标:word = dgo

输出:狗、神、教条megalogdon等...

最佳答案

您可以构建一个 Set<Character> word 中的所有字符,并迭代它。如果 dictionaryWord 中没有一个字符,然后dictionaryWord不适合。仅当全部出现时 - 打印 dictionaryWord

    String word = "dog";
String dictionaryWord;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while((dictionaryWord = br.readLine()) != null) {
Set<Character> chars = new HashSet<Character>();
for (char c : word.toCharArray()) {
chars.add(c);
}
boolean match = true;
for (Character c : chars) {
String s = "" + c;
if (!dictionaryWord.contains(s)) {
match = false;
break;
}
}
if (match == true)
System.out.println(dictionaryWord);
}

上面代码中,集合创建可以移出while当然是循环。

更有效的解决方案可能是创建一个 Set来自dictionaryWord同样,然后检查两个集合的交集是否与表示 word 的集合相同。
这将是:

    String word = "dog";
Set<Character> set1 = new HashSet();
for (char c : word.toCharArray()) {
set1.add(c);
}
String dictionaryWord;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while((dictionaryWord = br.readLine()) != null) {
Set<Character> set2 = new HashSet();
for (char c : dictionaryWord.toCharArray()) {
set2.add(c);
} Set<String> intersection = new HashSet(CollectionUtils.intersection(set1, set2));
if (set1.equals(intersection)) {
System.out.println(dictionaryWord);
} else System.out.println("bad");
}

使用 CollectionUtils.intersection() 来自 Apache 公共(public)资源

关于java - 如何找到至少一次包含所有给定字符的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10567702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com