題目:
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.
AC:
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
int strsLen = strs.length;
int len = strs[0].length();
int index = 0;
while (index < len) {
char ch = strs[0].charAt(index);
for (int i = 1; i < strsLen; i++) {
if (index >= strs[i].length() || strs[i].charAt(index) != ch) {
return strs[0].substring(0, index);
}
}
index++;
}
if (index == len) {
return strs[0].substring(0, index);
}
return "";
}