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