Skip to content

Commit

Permalink
Optimized the detection of potentially-overlapping strings
Browse files Browse the repository at this point in the history
  • Loading branch information
JoshyPHP committed Nov 4, 2019
1 parent 1975726 commit 68eef53
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/ShortestCommonSuperstring.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,19 +172,25 @@ protected function removeEmptyStrings(): void
*/
protected function removeFullyOverlappingStrings(): void
{
$strlen = array_map('strlen', $this->strings);
$i = count($this->strings);
while (--$i > 0)
// Copy the list of strings ordered by ascending length and create a master string by
// concatenating them all
$strings = array_reverse($this->strings, true);
$all = implode('', $strings);
$pos = 0;
foreach ($strings as $i => $str)
{
$str = $this->strings[$i];
$len = $strlen[$i];
// Test whether current string potentially appears in any subsequent, bigger strings
$pos += strlen($str);
if (strpos($all, $str, $pos) === false)
{
continue;
}

// Iterate over strings starting with the longest. Stop when we reach strings the size
// of the current string
// Iterate over strings from the longest to the one before current string
$j = -1;
while ($strlen[++$j] > $len)
while (++$j < $i)
{
if (strpos($this->strings[$j], $str) !== false)
if (strpos($strings[$j], $str) !== false)
{
unset($this->strings[$i]);
break;
Expand Down

0 comments on commit 68eef53

Please sign in to comment.