擅长:python、mysql、java
<p>这里有一个相当有效的方法使用regexp。代码是Perl编写的,但原则应该适用于其他语言:</p>
<pre><code>my $xor = "$first" ^ "$second"; # quotes force string xor even for numbers
$xor =~ /^\0*/; # match leading null characters
my $common_prefix_length = $+[0]; # get length of match
</code></pre>
<p>(一个值得注意的微妙之处是,Perl的string XOR操作符(<code>^</code>)实际上用空填充较短的字符串,以匹配较长字符串的长度。因此,如果字符串可能包含空字符,<em>和</em>如果短字符串恰好是长字符串的前缀,则使用此代码计算的公共前缀长度可能超过短字符串的长度。)</p>