Leetcode--Look for the longest common prefix (binary search method)

Write a function to find the longest common prefix in a string array.
If there is no public prefix, the empty string "" is returned.
Example 1:

输入: ["flower","flow","flight"]
输出: "fl"

Insert picture description here
startsWith (String s): Determine whether the string starts with the specified character or substring.

public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0)
        return "";
    int minLen = Integer.MAX_VALUE;
    for (String str : strs)
        minLen = Math.min(minLen, str.length());
    int low = 1;
    int high = minLen;
    while (low <= high) {
        int middle = (low + high) / 2;
        if (isCommonPrefix(strs, middle))
            low = middle + 1;
        else
            high = middle - 1;
    }
    return strs[0].substring(0, (low + high) / 2);
}

private boolean isCommonPrefix(String[] strs, int len){
    String str1 = strs[0].substring(0,len);
    for (int i = 1; i < strs.length; i++)
        if (!strs[i].startsWith(str1))
            return false;
    return true;
}

Published 6 original articles · liked 0 · visits 19

Guess you like

Origin blog.csdn.net/qq_44158395/article/details/105445461
Recommended