首页 > 代码库 > leetcode--Longest Common Prefix
leetcode--Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
public class Solution { public String longestCommonPrefix(String[] strs) { String prefix = ""; int length = strs.length; if(length > 0){ prefix = strs[0]; int prefixLength = strs[0].length(); for(int i = 1; i < length; ++i){ int k = 0; int strLength = strs[i].length(); for(int j = 0; j < Math.min(prefixLength, strLength); ++j){ if(prefix.charAt(j) == strs[i].charAt(j)) ++k; else break; } prefix = strs[i].substring(0, k); prefixLength = k; if( k == 0) break; } } return prefix; }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。