【发布时间】:2020-03-10 14:01:59
【问题描述】:
我有一些字符串数组,例如:
$big = ['html', 'body', 'div', 'table', 'tbody', 'tr', 'td'];
$small = ['body', 'div', 'td'];
$wrong = ['td', 'body', 'div'];
我需要检查$small 和$wrong 是否可以在$big 中找到。但是我需要顺序相同。所以我的函数应该为$small返回true,为$wrong返回false。手动完成应该相当简单,但我需要代码快速。因此,理想情况下,如果有一个内置功能可以实现这一点,我宁愿使用它。
所以问题主要是这样的内置是否存在。这是我想出的代码,以防万一:
/**
* Returns whether the substack is contained in the stack in the correct order.
*
* @param string[] $stack The substack to check
* @param string[] $subStack The substack to check
* @return bool
*/
function stackInStack(array $stack, array $subStack)
{
// First let's do a simple array diff to save time on an ordered diff;
// TODO: Check if this actually improves average performance.
if (count(array_diff($subStack, $stack)) !== 0) return false;
$stackSize = count($stack);
$subStackSize = count($subStack);
$stackIndex = 0;
for ($subIndex = 0; $subIndex < $subStackSize; $subIndex++) {
while (
$stackIndex < $stackSize &&
$stack[$stackIndex] !== $subStack[$subIndex]
) {
$stackIndex++;
}
if ($stackIndex == $stackSize) {
if ($subIndex <= $subStackSize - 1) {
return false;
} elseif ($subIndex > $subStackSize - 1) {
throw new Exception('Very Strange Exception: subIndex has outgrown subStacksize');
}
} elseif ($stackIndex > $stackSize) {
throw new Exception('Very Strange Exception: index has outgrown stacksize');
break;
}
}
return true;
}
如果内置不存在或速度很慢,任何提高上述代码效率的技巧(除了用 c 重写)也将不胜感激。
【问题讨论】:
-
喂?你放弃了吗???
标签: php arrays optimization php-7