首页 > 代码库 > Longest Common Prefix
Longest Common Prefix
Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
1 public class Solution { 2 public String longestCommonPrefix(String[] strs) { 3 String result = ""; 4 if(null == strs || 0 == strs.length) 5 return result; 6 7 int minLength = strs[0].length(); 8 boolean end = false; 9 for(int i = 1; i < strs.length; i++){10 minLength = minLength > strs[i].length() ? strs[i].length() : minLength;11 }//找出最小长度12 for(int i = 0; i < minLength && !end; i++){13 char ch = strs[0].charAt(i);//第i个字符14 for(int j = 1; j < strs.length;j++){//遍历所有字符串15 if(strs[j].charAt(i) != ch){16 end = true;17 }18 }19 if(!end)20 result += ch;21 }22 return result;23 }24 }
Longest Common Prefix
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。