标签:function amongst public common 字符串
Total Accepted: 44491 Total Submissions: 170999My Submissions
Question Solution
Write a function to find the longest common prefix string amongst an array of strings.
Show Tags
分析,最长公共前缀,首先找到最短的字符串的长度,作为度量尺寸,然后依次各个字符串分析每一个字符是否相同,相同则加入到最终结果集合中,不同停止,返回最终结果
public class Solution {
public String longestCommonPrefix(String[] strs) {
int count=strs.length;
String nullstr="";
if(count==0)
return nullstr;
if(count==1)
return strs[0];
int ml=strs[0].length();
for(int i=1;i<count;i++)
{
int l=strs[i].length();
if(l<ml)
ml=l;
}
if(ml==0)
return nullstr;
else
{
String s="";
int j=0;
for(int i=0;i<ml;i++)
{
for(j=1;j<count;j++)
if(strs[j].charAt(i)!=strs[j-1].charAt(i))
break;
if(j!=count)
break;
else
s=s+strs[j-1].charAt(i);
}
return s;
}
}
}
Leetcode#14Longest Common Prefix
标签:function amongst public common 字符串
原文地址:http://7061299.blog.51cto.com/7051299/1640493