最长公共前缀_LinkCode

给k个字符串,求出他们的最长公共前缀(LCP)


样例

在 "ABCD" "ABEF" 和 "ACEF" 中,  LCP 为 "A"

在 "ABCDEFG", "ABCEFG", "ABCEFA" 中, LCP 为 "ABC"

public class Solution {
    /**
     * @param strs: A list of strings
     * @return: The longest common prefix
     */
    public String longestCommonPrefix(String[] strs) {
        // write your code hereint k = strs.length;
		int k = strs.length;
		if(strs.length == 0)
			return "";
		if(strs.length == 1)
			return strs[0];
		String s = strs[0];
		String s_ = strs[1];
		int min = (strs[0].length() > strs[1].length())?strs[1].length():strs[0].length();
		for(int i=0;i<strs[0].length();i++)
		{
			s = strs[0].substring(0, min-i);
			s_  = strs[1].substring(0, min-i);
			if(s.equals(s_))
				break;
		}
		//System.out.println(s);
//		System.out.println("s:" + s);
		if(strs.length == 2)
			return s;
		else
		{
			for(int i=2;i<k;i++)
			{
				if(strs[i] == "")
					return "";
				while(true)
				{
					s_ = strs[i].substring(0, s.length());
					if (s_.equals(s)) {
						break;
					} else {
						s = strs[i].substring(0, s.length()-1);
					}
				}
			}
		}
		
		return s;
    }
}


你可能感兴趣的:(lintcode)