题解 | #最长公共前缀#
最长公共前缀
http://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
思路:挨个比较
1.设置一个列索引指针,每循环一次加1
2.循环体内for循环看当前字符串下标为col的字符是否与下一个字符串的下标为col的字符相等,不相等则返回res字符串。
3.for循环结束把下标为col的字符加入到res中。
public String longestCommonPrefix (String[] strs) {
// write code here
if(strs.length==0){
return "";
}
if(strs.length==1){
return strs[0];
}
StringBuilder res=new StringBuilder();
int col=0;
while(true){
for(int i=0;i<strs.length-1;i++){
//先判断一下当前字符串以及下一个字符串的长度是否大于列索引值
if(strs[i].length()>col && strs[i+1].length()>col){
//两个字符不相等,返回res
if(strs[i].charAt(col)!=strs[i+1].charAt(col)){
return res.toString();
}
}
//如果长度不够,直接返回
else{
return res.toString();
}
}
res.append(strs[0].charAt(col));
col++;
}
//这里不需要再返回了,因为while(true)是死循环,如果循环结束了,那么一定是因为返回了。
}