LeetCode14-最长公共前缀

题目链接

英文链接:https://leetcode.com/problems/longest-common-prefix/

中文链接:https://leetcode-cn.com/problems/longest-common-prefix/

题目详述

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 “”。

示例 1:

1
2
输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

1
2
3
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:

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

题目详解

  • 以第一个字符串为基准,逐个字符进行比较。
  • 如果发现字符串到末尾或者存在不相等的字符,直接返回。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class LeetCode_00014 {

public String longestCommonPrefix(String[] strs) {
if (strs == null || 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() || c != strs[j].charAt(i)) {
return strs[j].substring(0, i);
}
}
}
return strs[0];
}
}