思路:先对比前2个字符对象,找到公共前缀;再拿公共前缀和后面的字符对象对比,找到公共前缀;依次类推...
import java.util.*; public class Solution {
/**
*
* @param strs string字符串一维数组
* @return string字符串
*/
public String longestCommonPrefix (String[] strs) {
// write code here
if (strs.length == 0 || strs == null) return "";
int i = 1;
String privot = strs[0];
while (i < strs.length) {
//找到公共前缀
while (strs[i].indexOf(privot) != 0) {
privot = privot.substring(0, privot.length() - 1);
}
i++;
}
return privot;
}
}