Sparse Arrays

HackerRank 問題: Sparse Arrays

Question

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results.

HackerRank 問題: matchingStrings

Answer

<?php

/*
 * Complete the 'matchingStrings' function below.
 *
 * The function is expected to return an INTEGER_ARRAY.
 * The function accepts following parameters:
 *  1. STRING_ARRAY strings
 *  2. STRING_ARRAY queries
 */

function matchingStrings($search_strings, $query_string_array) {
    // find all search string count
    $string_mapping = [];
    foreach ($search_strings as $str) {
        if (!isset($string_mapping[$str])) {
            $string_mapping[$str] = 1;
            continue;
        }
        $string_mapping[$str]++;
    }

    // final query string count array
    $query_string_result = [];

    // find query string count in search string
    foreach ($query_string_array as $query_string) {
        $string_occur_times = 0;
        if (isset($string_mapping[$query_string])) {
            $string_occur_times = $string_mapping[$query_string];
        }

        $query_string_result[] = $string_occur_times;
    }

    return $query_string_result;

}

$fptr = fopen(getenv("OUTPUT_PATH"), "w");

$strings_count = intval(trim(fgets(STDIN)));

$strings = array();

for ($i = 0; $i < $strings_count; $i++) {
    $strings_item = rtrim(fgets(STDIN), "\r\n");
    $strings[] = $strings_item;
}

$queries_count = intval(trim(fgets(STDIN)));

$queries = array();

for ($i = 0; $i < $queries_count; $i++) {
    $queries_item = rtrim(fgets(STDIN), "\r\n");
    $queries[] = $queries_item;
}

$res = matchingStrings($strings, $queries);

fwrite($fptr, implode("\n", $res) . "\n");

fclose($fptr);

Reference