题意:
解题思路:
思路:
1. 以数组中第一个字符串做为比较对象,循环截取第1个字符串的第i个字符跟后面n个字符串的第i个字符做比较;
2. 当i大于后面字符串长度时,或者字符串不等时,终止;
PHP代码实现:
class Solution {
/**
* @param String[] $strs
* @return String
*/
function longestCommonPrefix1($strs) {
if ($strs == null || count($strs) == 0) return "";
if (count($strs) == 1) return $strs[0];
$first = $strs[0];
for ($i = 0; $i < strlen($first); ++$i) {
$c = $first[$i];
for ($j = 1; $j < count($strs); ++$j) {
if ($i >= strlen($strs[$j]) || $strs[$j][$i] != $c) {
return substr($first, 0, $i);
}
}
}
return $first;
}
function longestCommonPrefix($strs) {
return $this->longestCommonPrefix1($strs);
if (!$strs) return '';
if (count($strs) == 1) return $strs[0];
$min = strlen($strs[0]);
$key = 0;
foreach ($strs as $k => $str) {
if (strlen($str) <= $min) {
$key = $k;
$min = strlen($str);
}
}
$minStr = $strs[$key];
unset($strs[$key]);
$left = 1;
$right = strlen($minStr);
while ($left <= $right) {
$mid = $left + floor(($right - $left) / 2);
if ($this->isPrefix($strs, substr($minStr, 0, $mid))) {
$left = $mid + 1;
} else {
$right = $mid - 1;
}
}
return substr($minStr, 0, min($left, $right));
}
function isPrefix($strs, $prefix) {
foreach ($strs as $s) {
if (substr($s, 0, strlen($prefix)) != $prefix) {
return false;
}
}
return true;
}
}
GO代码实现:
func longestCommonPrefix(strs []string) string {
if len(strs) == 0 {
return ""
}
for i := 0; i < len(strs[0]); i++ {
for j := 1; j < len(strs); j++ {
if i >= len(strs[j]) || strs[j][i] != strs[0][i] {
return strs[0][:i]
}
}
}
return strs[0]
}