You can build a Set<Character>
of all the chars in word
, and iterate it. If one character is not in dictionaryWord
, then dictionaryWord
does not fit. Only if all appear - print 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);
}
In the above code, the set creation can be moved out of the while
loop, of course.
More efficient solution could be to create a Set
from dictionaryWord
as well, and then check if the intersection of the two sets is identical to the set representing word
.
This will be:
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");
}
using CollectionUtils.intersection()
from apache commons