Untitled
unknown
plain_text
3 years ago
2.4 kB
7
Indexable
public class Solution {
public static List<Long> substitutions(List<String> words, List<String> phrases) {
Map<String, Integer> wordCount = new HashMap<>();
Map<String, Integer> anagramCount = new HashMap<>();
List<Long> result = new ArrayList<>();
for (String word : words) {
char[] chars = word.toCharArray();
java.util.Arrays.sort(chars);
String sortedWord = new String(chars);
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
anagramCount.put(sortedWord, anagramCount.getOrDefault(sortedWord, 0) + 1);
}
for (String phrase : phrases) {
String[] wordsInPhrase = phrase.split(" ");
long total = 1;
for (String wordInPhrase : wordsInPhrase) {
char[] chars = wordInPhrase.toCharArray();
java.util.Arrays.sort(chars);
String sortedWord = new String(chars);
total *= anagramCount.get(sortedWord) / wordCount.get(wordInPhrase);
}
result.add(total);
}
return result;
}
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int wordsCount = Integer.parseInt(bufferedReader.readLine().trim());
List<String> words = IntStream.range(0, wordsCount).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
})
.collect(toList());
int phrasesCount = Integer.parseInt(bufferedReader.readLine().trim());
List<String> phrases = IntStream.range(0, phrasesCount).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
})
.collect(toList());
List<Long> result = substitutions(words, phrases);
bufferedWriter.write(
result.stream()
.map(Object::toString)
.collect(joining("\n"))
+ "\n"
);
Editor is loading...