题目
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.length==0) return "";
if(strs.length==1) return strs[0];
String commonPrefix="";
boolean end=true;
char strChar[]=strs[0].toCharArray();
ok:
for (int j = 0;j<strChar.length;j++){
for(int i=1;i<strs.length;i++){
char tempChar[]=strs[i].toCharArray();
int tempChar_length=tempChar.length;
if(j<tempChar_length){
if(tempChar[j]==strChar[j]){
}
else{
break ok;
}
}
else{
break ok;
}
}
commonPrefix+=strChar[j];
}
return commonPrefix;
}
}
/********************************
* 本文来自博客 “李博Garvin“
* 转载请标明出处:http://blog.csdn.net/buptgshengod
******************************************/

本博客提供了一个函数,用于找出给定字符串数组中最长的公共前缀字符串。通过遍历数组中的字符,该函数能高效地确定所有字符串共享的最长起始部分。

被折叠的 条评论
为什么被折叠?



