您的位置:首页 > 其它

【LeetCode】014.Longest Common Prefix

2015-03-26 12:45 323 查看
题目如下:

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 == null || strs.length == 0)
return "";
String st = strs[0];
int length = 0;
for(int i=1;i<strs.length;i++){
length = lcp(st,strs[i]);
if(length == 0)
return "";
st = st.substring(0,length);
}
return st;
}

// find the (index + 1) of the end char of the common prefix,0 means null
public int lcp(String str1,String str2){
int i = 0;
for(;i<str1.length() && i<str2.length();i++){
if(str1.substring(i, i+1).equals(str2.substring(i,i+1)))
continue;
else
break;
}
return i;
}

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