来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix/
描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入: [“flower”,”flow”,”flight”]
输出: “fl”
示例 2:
输入: [“dog”,”racecar”,”car”]
输出: “”
解释: 输入不存在公共前缀。
题解
class Solution {public String longestCommonPrefix(String[] strs) {if (null == strs || strs.length == 0) return "";String prefix = strs[0];for (int i = 1; i < strs.length; i++) {while (strs[i].indexOf(prefix) != 0) {prefix = prefix.substring(0, prefix.length() - 1);if (prefix.isEmpty()) return "";}}return prefix;}}
class Solution {public String longestCommonPrefix(String[] strs) {if (null == strs || strs.length == 0) return "";for (int i = 0; i < strs[0].length(); i++) {char c = strs[0].charAt(i);for (int j = 1; j < strs.length; j++) {if (i == strs[j].length() || strs[j].charAt(i) != c) {return strs[0].substring(0, i);}}}return strs[0];}}
复杂度分析
- 时间复杂度:
,S是所有字符串中字符数量的总和。
最坏的情况下,n个字符串都是相同的;
最好的情况下,第二个算法只需进行次比较,其中
是数组中最短字符串的长度;
- 空间复杂度:
