第十题 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
法一
class Solution {
public String
longestCommonPrefix(String
[] strs
) {
if(strs
== null
|| strs
.length
== 0) return "";
String prefix
= strs
[0];
for(String s
: strs
){
while(s
.indexOf(prefix
) != 0) prefix
= prefix
.substring(0, prefix
.length() - 1);
}
return prefix
;
}
}
注1:substring(0,0)截取不到内容,但是不会报错。 注2:indexOf()的用法 public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
法二
class Solution {
public String
longestCommonPrefix(String
[] strs
) {
if(strs
== null
|| strs
.length
== 0) return "";
Arrays
.sort(strs
);
String wordOne
= strs
[0];
String wordTwo
= strs
[strs
.length
- 1];
while(wordTwo
.indexOf(wordOne
) != 0) wordOne
= wordOne
.substring(0, wordOne
.length() - 1);
return wordOne
;
}
}
注:该方法先将strs进行排序,排好后的顺序是按照每个字母的顺序排序,从而可以直接取第一个单词跟最后一个单词进行比较。