Longest Common Prefix

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

Example

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 "";
        
        int n=strs.length;
        char[] res=strs[0].toCharArray();
        if(res==null ||res.length==0) return "";
        int m=res.length;

        for(int i=1;i<n;i++)
        {
            char[] c=strs[i].toCharArray();
            if(c==null || c.length==0) return "";
            m=Math.min(m,c.length);
            char[] c1=new char[m];
            for(int j=0;j<m;j++)
            {
                if(c[j]==res[j])
                {
                    c1[j]=c[j];
                }
                else
                {
                    res=c1;
                    continue;
                }
            }
        }
       
        return String.valueOf(res).trim();
    }
    
}

 

posted on 2016-01-16 05:02  一心一念  阅读(186)  评论(0)    收藏  举报

导航