题目:
分析:直接两两进行比较,用res保存当前最长的公共前缀。下一个将当前字符串与它进行比较,然后更新res。
public class Solution {
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
public String longestCommonPrefix(String[] strs) {
// write your code here
if(strs==null || strs.length==0) return "";
String res=strs[0];
for(int i=1;i<strs.length;i++){
String temp=res;
String cur=strs[i];
res="";
int index=0;
while(index<Math.min(temp.length(),cur.length()) && temp.charAt(index)==cur.charAt(index)){
res+=temp.charAt(index++);
}
}
return res;
}
}