您可以在 中构建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
from 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 commons使用