来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix/

描述

编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。

示例 1:
输入: [“flower”,”flow”,”flight”]
输出: “fl”

示例 2:
输入: [“dog”,”racecar”,”car”]
输出: “”
解释: 输入不存在公共前缀。

说明:
所有输入只包含小写字母 a-z 。

题解

  1. class Solution {
  2. public String longestCommonPrefix(String[] strs) {
  3. if (null == strs || strs.length == 0) return "";
  4. String prefix = strs[0];
  5. for (int i = 1; i < strs.length; i++) {
  6. while (strs[i].indexOf(prefix) != 0) {
  7. prefix = prefix.substring(0, prefix.length() - 1);
  8. if (prefix.isEmpty()) return "";
  9. }
  10. }
  11. return prefix;
  12. }
  13. }
  1. class Solution {
  2. public String longestCommonPrefix(String[] strs) {
  3. if (null == strs || strs.length == 0) return "";
  4. for (int i = 0; i < strs[0].length(); i++) {
  5. char c = strs[0].charAt(i);
  6. for (int j = 1; j < strs.length; j++) {
  7. if (i == strs[j].length() || strs[j].charAt(i) != c) {
  8. return strs[0].substring(0, i);
  9. }
  10. }
  11. }
  12. return strs[0];
  13. }
  14. }

复杂度分析

  • 时间复杂度:14. 最长公共前缀(Longest Common Prefix) - 图1,S是所有字符串中字符数量的总和。

最坏的情况下,n个字符串都是相同的;
最好的情况下,第二个算法只需进行14. 最长公共前缀(Longest Common Prefix) - 图2次比较,其中14. 最长公共前缀(Longest Common Prefix) - 图3是数组中最短字符串的长度;

  • 空间复杂度:14. 最长公共前缀(Longest Common Prefix) - 图4