我会选择以下内容。
拆分字符串以获得每个单独的字符,并使用值翻转键,使所有单独的字符都是键。 (使用array_flip)
现在我们可以使用带有一些基本集合操作的键,例如array_intersect_key 来获取交集以获取两个字符串中的字符。
我们可以应用array_diff_key 来获取集合的差异(因此第一个字符串中的那些字符而不是另一个字符串中的那些字符)。
$s1 = array_flip(str_split('postcard'));
$s2 = array_flip(str_split('car'));
$intersection = array_intersect_key($s1, $s2);
$difference = array_diff_key($s1, $s2);
echo 'Letters in common: ' . implode(' - ', array_keys($intersection)) . PHP_EOL;
echo 'Letters NOT in common: ' . implode(' - ', array_keys($difference)) . PHP_EOL;
上面确实是为了吐出独特的字符(注释集)。下面的一段代码我假设是你想要实现的:
function outputResult(string $s, bool $inCommon = true)
{
$result = 'Letters';
if (!$inCommon) {
$result .= ' NOT';
}
$result .= ' in common: ';
$result .= !empty($s) ? implode(' - ', str_split($s)) : 'NONE';
echo $result . PHP_EOL;
}
// Count for both the occurrences of each char.
$s1 = array_count_values(str_split('paccoi'));
$s2 = array_count_values(str_split('coi'));
$mostUniqueChars = $s1;
$leastUniqueChars = $s2;
// For now I assumed the string with most unique characters
// is the one you want to test. Could ofcourse output them both
// ways if you wrap all logic in a function. (note that intersection
// is the same both ways)
if (count($s2) > count($s1)) {
$mostUniqueChars = $s2;
$leastUniqueChars = $s1;
}
$intersect = '';
$diff = '';
foreach ($mostUniqueChars as $char => $count) {
// Get the number of characters in common (and how frequent)
$common = min($count, ($leastUniqueChars[$char] ?? 0));
// As an alternative you could add common and difference to an array to keep
// the counts, but I chose to repeat it and concat it to a string.
if ($common > 0) {
$intersect .= str_repeat($char, $common);
}
// Calculate the difference between first string and second string
// in case difference has a value <= 0 then string 2 had more occurrences
// of the character.
$difference = $count - ($leastUniqueChars[$char] ?? 0);
if ($difference > 0) {
$diff .= str_repeat($char, $difference);
}
};
// Note that both strings $intersect and $diff contain
// all the characters, you could also output these directly.
outputResult($intersect);
outputResult($diff, $inCommon = false);
输出:
Letters in common: c - o - i
Letters NOT in common: p - a - c