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
.
public String longestCommonPrefix(String[] strs) {
if (strs.length==0) return "";
String pre = strs[0];
for (int i = 0; i < strs.length; i++) {
while (strs[i].indexOf(pre)!=0)
pre = pre.substring(0,pre.length()-1);
}
return pre;
}
indexof:
查找字串中指定字符或字串首次出现的位置,返首索引值,如:
str1.IndexOf("字"); //查找“字”在str1中的索引值(位置)
str1.IndexOf("字串");//查找“字串”的第一个字符在str1中的索引值(位置)
str1.IndexOf("字",start,end);//从str1第start+1个字符起,查找end个字符,查找“字”在字符串STR1中的位置[从第一个字符算起]注意:start+end不能大于str1的长度
indexof参数为string,在字符串中寻找参数字符串第一次出现的位置并返回该位置。如string s="0123dfdfdf";int i=s.indexof("df");这时i==4。
思路:把前缀pre设置为数组中的第一个字符,与其余字符进行比对,当pre在其余字符中的位置不为零时,表明pre不是其他数组内字符的前缀,去掉pre最后一个字符重新比对,直到找到公共前缀为止。