检查两个阵列是否为"0";几乎相等";(一个可以转换为另一个)


Check if two arrays are "almost equal" (one can be transformed to the other)

我遇到了一个面试问题,但我无法解决,我认为这是一个合适的问题。

问题的前提是检查两个数组是否"大致相等"。

背景:

您将得到两个数组A和B,其中包含count(B) >= count(A)。A和B中的元素是包含字母字符的字符串,可能还有一个SET花括号。

示例:

A = {'Hello', 'World', 'This is {cool}'}
B = {'Hello', 'World', 'This is {cool}', '{This is cool}'}

'{This is {cool}}这样的东西永远不会出现,因为它有两组大括号。

如果:,则称阵列A和B"大致相等">

  • B包含A中的所有元素
  • B中不在A中的每个元素都可以通过将花括号应用于A中的元素(Hello => {Hello}(或通过将A中元素内的花括号移动到元素外部(This is {cool} => {This is cool}(来获得

编写一个函数来确定两个数组a和B是否"大致相等"。注重效率。

我天真的解决方案:

我写了一个函数,从a中删除一个元素,检查该元素是否出现在B中,以及该元素的任何"排列"是否出现在B.如果出现,则从B.中删除它们。最后,如果a和B都为空,我返回true。我想知道是否有更有效的解决方案。

B包含A 中的所有元素

这可以使用array_diff:实现

if (array_diff($a, $b) == array()) {
    // Check #1: pass
}

来自手册:

将array1与一个或多个其他数组进行比较,并返回array1中任何其他数组中都不存在的值。

因此,如果$a中存在$b中不存在的值,则上述检查将返回错误


B中不在A中的每个元素都可以通过将花括号应用于A中的元素(Hello=>{Hello}(或通过将A中元素内的花括号移动到元素外部(This is {cool}=>{This is cool}(来获得

我曾希望通过比较完全去掉括号的两个数组来实现这一点,但规则or by moving the curly brackets within an element in A to the outside of the element表明,如果它围绕另一个单词,它应该失败。

事实并非如此,但您仍然可以移除大括号,并将其放回每个字符串的边缘进行比较:

/**
 * Remove any braces in the value and put them back in at the edges of the string
 * @param  string $value
 * @return string
 */
function addOrMoveBraces($value)
{
    return sprintf('{%s}', str_replace(['{', '}'], '', $value));;
}
$aWithBraces = array_map('addOrMoveBraces', $a);
$bWithBraces = array_map('addOrMoveBraces', $b);
if (array_diff($bWithBraces, $aWithBraces) == array()) {
    // Check #2: pass
}

把它放在一起

你需要一个函数,所以你可以这样做:

/**
 * Remove any braces in the value and put them back in at the edges of the string
 * @param  string $value
 * @return string
 */
function addOrMoveBraces($value)
{
    return sprintf('{%s}', str_replace(['{', '}'], '', $value));;
}
function justAboutEqual($a, $b)
{
    // Check #1
    if (array_diff($a, $b) == array()) {
        return true;
    }
    // Check #2
    if (array_diff(array_map('addOrMoveBraces', $b), array_map('addOrMoveBraces', $a)) == array()) {
        return true;
    }
    return false;
}

下面是针对这些函数的几个简单单元测试。

相关文章: