【LeetCode算法-14】Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
.
思路:
根据第一个字符串,不断去循环判断后面的字符串
代码:
class Solution {
public String longestCommonPrefix(String[] strs) {
if(null == strs || strs.length == 0){
return "";
}else if(strs.length == 1){
return strs[0];
}
String result = "";
for(int i = 1;i<=strs[0].length();i++){
String prefix = strs[0].substring(0,i);
for(int j=1;j<strs.length;j++){
if(strs[j].startsWith(prefix)){
if(j==strs.length-1){
result = prefix;
}
}else{
break;
}
}
}
return result;
}
}
String.substring(0,x),第二个参数很神奇,x就算超过字符串的长度也没关系,所以不用担心数组越界问题