【问题描述】
Write a function to find the longest common prefix string amongst an array of strings.
Subscribe to see which companies asked this question
【思路】
求最长公共前缀长度。
每次string元素与prefix比较,存储新的公共前缀。
【code】
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length <= 0) {
return "";
}
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
String curr = strs[i];
int len = Math.min(prefix.length(), curr.length());
int j;
for (j = 0; j < len; j++) {
if (prefix.charAt(j) != curr.charAt(j)) {
break;
}
}
prefix = prefix.substring(0, j);
}
return prefix;
}
}