码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Common Prefix

时间:2016-01-16 07:36:37      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

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();
    }
    
}

 

Longest Common Prefix

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/5134882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!