首页 > 代码库 > 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;      }}