首页 > 代码库 > Longest Common Prefix

Longest Common Prefix

题目

Write a function to find the longest common prefix string amongst an array of strings.

方法

从第一个字符开始,判断是否相同。
	    public String longestCommonPrefix(String[] strs) {
	        if (strs == null) {
	            return null;
	        }
	        if (strs.length == 0) {
	            return "";
	        }
	        if (strs.length == 1) {
	            return strs[0];
	        }
	        
	        int len = strs.length;
	        String lcp = "";
	        int i = 0;
	        boolean flag = true;
	        while (flag) {
	            char ch;
	            if (strs[0].length() > i) {
	                ch = strs[0].charAt(i);
	                for (int k = 1; k < len; k++) {
	                    if (strs[k].length() > i) {
	                        int temp = strs[k].charAt(i);
	                        if (temp != ch) {
	                            flag = false;
	                            break;
	                        }
	                    } else {
	                        flag = false;
	                        break;
	                    }
	                }
	                if (flag) {
	                    lcp += ch;
	                    i++;
	                }

	            } else {
	                flag = false;
	            }

	        }
	        return lcp;
	    }