• + 0 comments

    PHP solution:

    $_fp = fopen("php://stdin", "r");
    $numSentences = (int) fgets(STDIN);
    $sentences = array();
    for ($i = 0; $i < $numSentences; $i++) {
        $sentences[] = trim(fgets(STDIN));
    }
    $numWords = (int) fgets(STDIN);
    $words = array();
    for ($i = 0; $i < $numWords; $i++) {
        $words[] = trim(fgets(STDIN));
    }
    
    // Count occurrences of each word in all sentences
    $results = array();
    foreach ($words as $word) {
        $results[$word] = 0;
        foreach ($sentences as $sentence) {
          $pattern = '/(?<![a-zA-Z0-9_])(' . $word . ')(?![a-zA-Z0-9_])/';
            $numMatches = preg_match_all($pattern, $sentence, $matches);
            $results[$word] += $numMatches;
        }
    }
    
    // Print results
    foreach ($results as $word => $count) {
        echo $count . "\n";
    }
    fclose($_fp);