Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

Solution:

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0 || strs[0].length()==0) return "";
        int len = strs[0].length();
        for(int i=1; i<strs.length; i++){
            int j=0;
            while(j<len && j<strs[i].length() && strs[i-1].charAt(j)==strs[i].charAt(j)) j++;
            len = Math.min(len,j);
            if(len==0) break;
        }
        return strs[0].substring(0,len);
    }
}
comments powered by Disqus