14 Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
String longcommon = strs[0];
for (int i = 1; i < strs.length; i++) {
if (longcommon.length() > strs[i].length()) {
longcommon = longcommon.substring(0, strs[i].length());
}
for (int j = 0; j < strs[i].length(); j++) {
if (j >= longcommon.length()) {
break;
}
if (longcommon.charAt(j) != strs[i].charAt(j)) {
longcommon = longcommon.substring(0, j);
}
}
}
return longcommon;
}
}
浙公网安备 33010602011771号