Last active
August 29, 2015 14:07
-
-
Save zigo928/5b1a74ba91f62233d939 to your computer and use it in GitHub Desktop.
两个字符串都存在的最长的相同的字符串
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function longestCommonSubstring($str_a, $str_b, $case_sensitive = false) | |
{ | |
$len_a = mb_strlen($str_a); | |
$len_b = mb_strlen($str_b); | |
if (! $len_a || ! $len_b) { | |
return false; | |
} | |
if ($len_b < $len_a) { | |
list($len_a, $len_b) = array($len_b, $len_a); | |
list($str_a, $str_b) = array($str_b, $str_a); | |
} | |
if (! $case_sensitive) { | |
$str_a = strtolower($str_a); | |
$str_b = strtolower($str_b); | |
} | |
$ret = array(); | |
array_unshift($ret, ''); | |
for ($i = 0; $i < $len_a; $i++) { | |
$c = mb_substr($str_a, $i, 1); | |
if ($c === mb_substr($str_b, $i, 1)) { | |
$ret[0] .= $c | |
} else { | |
array_unshift($ret, ''); | |
} | |
} | |
usort($ret, function($a, $b) { | |
if (mb_strlen($a) === mb_strlen($b)) { | |
return strcmp($a, $b); | |
} | |
return mb_strlen($a) > mb_strlen($b) ? -1 : 1; | |
}); | |
return array_pop($ret); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment