[LeetCode] 14. Longest Common Prefix

时间:2022-01-10 14:03:25

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 == null || strs.length == 0) {
return "";
} else if (strs.length < 2) {
return strs[0];
} String r = strs[0];
int index = r.length();
for (int i = 1; i < strs.length; i++) {
int j = 0;
for (; j < strs[i].length() && j < index; j++) {
if (strs[i].charAt(j) != r.charAt(j)) {
break;
}
}
if (j == 0) {
return "";
}
index = j;
} return r.substring(0, index);
}
}