1. 程式人生 > >LeetCode 14. Longest Common Prefix

LeetCode 14. Longest Common Prefix

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

If there is no common prefix, return an empty string "".

Note:

All given inputs are in lowercase letters a-z.

public class LongestCommonPrefixSolution {
    public String longestCommonPrefix(String[] strs) {

        //基本思路為貪心演算法,每兩個元素取最長的公共元素,依次往下進行
        if (strs.length > 0) {
            String result = strs[0];
            int len = strs.length;

            for (int j = 1; j < len; j++) {
                while (!strs[j].startsWith(result)) {
                    result = result.substring(0, result.length() - 1);
                }
            }
            return result;
        } else {
            return "";
        }
    }

}