标签:
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(); } }
标签:
原文地址:http://www.cnblogs.com/kittyamin/p/5134882.html