您的位置:首页 > 其它

字符串数组的最长公共前缀

2013-12-31 10:08 701 查看
题目原型:

Write a function to find the longest common prefix string amongst an array of strings.

分别字符串数组中的每个字符串进行扫描对比,设置一个临时变量保存每次的比较的结果。

//取得两个字符串的最长公共前缀
public String getLongestStr(String one , String two)
{
//考虑为空的情况
if(one.length()==0||two.length()==0)
return "";
String common = "";
for(int i =0 ;i<one.length()&&i<two.length();i++)
{
if(one.substring(0, i+1).equals(two.substring(0, i+1)))
{
common = one.substring(0, i+1);
}
}
return common;
}
public String longestCommonPrefix(String[] strs)
{
//考虑为空的情况
if(strs.length==0)
return "";
boolean flag = false;
for(String s : strs)
{
if(s.length()==0||s==null||s.equals(""))
flag = true;
}
if(flag)
return "";
String longestCommStr = null;

longestCommStr = strs[0];
for(String str : strs)
{
if(longestCommStr.equals(""))
return "";
longestCommStr = getLongestStr(longestCommStr, str);
}
return longestCommStr;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: