您的位置:首页 > 其它

leetcode 14. Longest Common Prefix

2016-05-04 09:46 483 查看
//Write a function to find the longest common prefix string amongst an array of strings.

public class Solution {

public static void main(String[] args) {
String[] a = {"qweaqw","qweazxc","qweaz"};
String result = find(a);
System.out.println(result);
}

public static String find(String[] strs) {
String result = "";
boolean flag = true;
if(strs.length == 0){									//若输入空数组,则返回空串
return "";
}
int length = strs[0].length();
for(int i = 1;i<strs.length;i++){						//确定字符串数组中长度最小的字符串长度
if(length>strs[i].length()){
length = strs[i].length();
}
}
int j = 0;
while(j<length){										//逐个字符遍历所有字符串
char a = strs[0].charAt(j);
for(int i = 1;i<strs.length;i++){
if(a != strs[i].charAt(j)){
flag = false;								//若从某个字符不相等,跳出循环
break;
}
}
if(flag == false){
break;
}
result = result+a;									//若都相等,则最终字符串加上相等字符
j++;
}
return result;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: