描述
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.
解决方案
思路:从第二个字符串开始,都与第一个字符串比较相同位置的字符,如果相同,则指针向后移一位,否则,返回第一个字符串从0开始,到n-1截取即是最长公共前缀。
public String longestCommonPrefix(String[]strs){
if(strs==null||strs.length==0)return "";
int preCount=0;
boolean exit = false;
while(true){
if(strs[0].length()==preCount){
break;
}
char a=strs[0].charAt(preCount);
for(int i=1;i<strs.length;i++)
if(strs[i].length()==preCount||a!=strs[i].charAt(preCount)){
exit = true;
}
}
if(exit){
break;
}
preCount++;
}
return strs[0].substring(0,preCount);
}