LeetCode算法题-- 最长公共前缀
- 题目来源:https://leetcode-cn.com/problems/longest-common-prefix/solution/
题目要求
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:
示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
题目思路:
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0){
return "";
}
String first = strs[0];
for(int i = 0; i < strs.length; ++i){
while(strs[i].indexOf(first) != 0){
first = first.substring(0, first.length() - 1);
if(first.isEmpty()){
return "";
}
}
}
return first;
}
}
执行结果:
两个API:
- substring(start,stop),如果stop或start为负数,则置为0,若start >stop,则二者会互换。
- indexOf(str),返回第一次出现str的下标,若无,则为-1.