检查两个数组是否“几乎相等”(一个可以转换为另一个)

时间:2016-08-04 22:28:00

标签: php arrays algorithm

我有一个我无法得到的面试问题,我认为这是一个正确的问题。

问题的前提是检查两个数组是否“差不多”。

背景

您将获得两个数组A和B,其中包含count(B) >= count(A)。 A和B中的元素是包含字母字符的字符串,可能包含ONE 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。我想知道是否有更有效的解决方案。

1 个答案:

答案 0 :(得分:2)

  

B包含A

中的每个元素

这可以使用array_diff

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

从手册:

  

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

因此,如果$a中的值不存在于$b中,那么上面的检查将返回false

  

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;
}

Here's a couple of simple unit tests针对这些功能。

相关问题