题意:

image.png

解题思路:

  1. 思路:
  2. 1. 以数组中第一个字符串做为比较对象,循环截取第1个字符串的第i个字符跟后面n个字符串的第i个字符做比较;
  3. 2. i大于后面字符串长度时,或者字符串不等时,终止;

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param String[] $strs
  4. * @return String
  5. */
  6. function longestCommonPrefix1($strs) {
  7. if ($strs == null || count($strs) == 0) return "";
  8. if (count($strs) == 1) return $strs[0];
  9. $first = $strs[0];
  10. for ($i = 0; $i < strlen($first); ++$i) {
  11. $c = $first[$i];
  12. for ($j = 1; $j < count($strs); ++$j) {
  13. if ($i >= strlen($strs[$j]) || $strs[$j][$i] != $c) {
  14. return substr($first, 0, $i);
  15. }
  16. }
  17. }
  18. return $first;
  19. }
  20. function longestCommonPrefix($strs) {
  21. return $this->longestCommonPrefix1($strs);
  22. if (!$strs) return '';
  23. if (count($strs) == 1) return $strs[0];
  24. $min = strlen($strs[0]);
  25. $key = 0;
  26. foreach ($strs as $k => $str) {
  27. if (strlen($str) <= $min) {
  28. $key = $k;
  29. $min = strlen($str);
  30. }
  31. }
  32. $minStr = $strs[$key];
  33. unset($strs[$key]);
  34. $left = 1;
  35. $right = strlen($minStr);
  36. while ($left <= $right) {
  37. $mid = $left + floor(($right - $left) / 2);
  38. if ($this->isPrefix($strs, substr($minStr, 0, $mid))) {
  39. $left = $mid + 1;
  40. } else {
  41. $right = $mid - 1;
  42. }
  43. }
  44. return substr($minStr, 0, min($left, $right));
  45. }
  46. function isPrefix($strs, $prefix) {
  47. foreach ($strs as $s) {
  48. if (substr($s, 0, strlen($prefix)) != $prefix) {
  49. return false;
  50. }
  51. }
  52. return true;
  53. }
  54. }

GO代码实现:

  1. func longestCommonPrefix(strs []string) string {
  2. if len(strs) == 0 {
  3. return ""
  4. }
  5. for i := 0; i < len(strs[0]); i++ {
  6. for j := 1; j < len(strs); j++ {
  7. if i >= len(strs[j]) || strs[j][i] != strs[0][i] {
  8. return strs[0][:i]
  9. }
  10. }
  11. }
  12. return strs[0]
  13. }