lintcode-medium-Longest Common Prefix

Given k strings, find the longest common prefix (LCP).

For strings "ABCD""ABEF" and "ACEF", the LCP is "A"

For strings "ABCDEFG""ABCEFG" and "ABCEFA", the LCP is "ABC"

 

public class Solution {
    /**
     * @param strs: A list of strings
     * @return: The longest common prefix
     */
    public String longestCommonPrefix(String[] strs) {
        // write your code here
        
        if(strs == null || strs.length == 0)
            return "";
        
        if(strs.length == 1)
            return strs[0];
        
        int min = Integer.MAX_VALUE;
        
        for(int i = 0; i < strs.length; i++)
            if(strs[i].length() < min)
                min = strs[i].length();
        
        StringBuilder result = new StringBuilder();
            
        for(int i = 0; i < min; i++){
            char c = strs[0].charAt(i);
            
            for(int j = 1; j < strs.length; j++){
                if(strs[j].charAt(i) != c)
                    return result.toString();
            }
            
            result.append(c);
        }
        
        return result.toString();
    }
}

 

posted @ 2016-03-26 01:57  哥布林工程师  阅读(161)  评论(0编辑  收藏  举报