题目描述:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
代码:
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return \"\";
} else if (strs.length == 1) {
return strs[0];
} else if (strs[0] == null || strs[0].length() == 0) {
return \"\";
} else {
String head = \"\";
for (int i = 0; i < strs[0].length(); i++) {
head = strs[0].substring(0, i + 1);
for (int j = 1; j < strs.length; j++) {
if (!strs[j].startsWith(head)) {
return strs[0].substring(0, i);
}
}
}
return head;
}
}
}
执行时长:12ms
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。




