14. Longest Common Prefix

来源:互联网 发布:预包装食品网络销售 编辑:程序博客网 时间:2024/06/08 08:24

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


Solution:

Tips:

two-way merge sort


Java Code:

public class Solution {    public String longestCommonPrefix(String[] strs) {        if (strs.length < 1) {            return "";        }                return longestCommonPrefix(strs, 0, strs.length - 1);    }        private String longestCommonPrefix(String[] strs, int begin, int end) {        if (end < begin) {            return "";        }        if (begin == end) {            return strs[begin];        }        int middle = begin + (end - begin) / 2;        String left = longestCommonPrefix(strs, begin, middle);        String right = longestCommonPrefix(strs, middle + 1, end);        int i = 0;        while (i < left.length() && i < right.length()) {            if (left.charAt(i) != right.charAt(i)) {                break;            }            i++;        }        return left.substring(0, i);    }}


0 0