How to check if a string can be constructed by using the letters of another string in PHP

1 Answer

0 votes
function canConstruct(string $str, string $anotherStr): bool {
    // ASCII frequency table
    $freq = array_fill(0, 256, 0);

    // Count characters in anotherStr
    for ($i = 0; $i < strlen($anotherStr); $i++) {
        $ch = ord($anotherStr[$i]);
        $freq[$ch]++;
    }

    // Check if str can be constructed
    for ($i = 0; $i < strlen($str); $i++) {
        $ch = ord($str[$i]);
        $freq[$ch]--;
        if ($freq[$ch] < 0) {
            return false;
        }
    }

    return true;
}

$str = "hello";
$anotherStr = "olehhlxyz";

echo canConstruct($str, $anotherStr) ? "true" : "false";



/*
run:

true

*/

 



answered Jan 5 by avibootz

Related questions

...