题解 | #最长公共前缀#
最长公共前缀
http://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
import java.util.*;
public class Solution {
/**
*
* @param strs string字符串一维数组
* @return string字符串
*/
public String longestCommonPrefix (String[] strs) {
// write code here
if(strs.length==0)
return "";
StringBuilder sb=new StringBuilder(strs[0]);
int len=sb.length();
for(int i=1;i<strs.length;i++)
{
int count=0;
for(int j=0;j<strs[i].length()&& j<len;j++)
{
if(sb.charAt(j)!=strs[i].charAt(j))
{
break;
}
count++;
}
len=Math.min(len,count);
}
String ret=new String(sb);
return ret.substring(0,len);
}
}
OPPO公司福利 1195人发布