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.
solution 1:
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
String pre = strs[0];
int i = 1;
while(i < strs.length){
while(strs[i].indexOf(pre) != 0)
pre = pre.substring(0,pre.length()-1);
i++;
}
return pre;
}
知识点:
s.indexof(string str) 返回s中str出现的首位的索引,如果没有则返回-1。
solution2:
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null) return null;
if(strs.length == 0) return "";
Arrays.sort(strs);
int i = 0;
while (i < strs[0].length() && strs[0].charAt(i) == strs[strs.length - 1].charAt(i)) i++;
return strs[0].substring(0, i);
}
}
知识点:
Arrays.sort(strs) 排序 不一定按长度
.charAt() 返回第i位的值
.substring(int i, int j);