Monday, May 19, 2014

Leetcode: 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)
            return "";
        outerloop:
        for(int i=strs[0].length(); i>0; i--)
        {
            String prefix = strs[0].substring(0,i);
            for(int j=1; j<strs.length; j++)
            {
                if(strs[j].length()<i || ! strs[j].substring(0,i).equals(prefix))
                    continue outerloop;
            }
            return prefix;
        }
        return "";
    }
}

No comments :

Post a Comment