📜  使用分而治之算法的最长公共前缀

📅  最后修改于: 2021-09-16 11:14:50             🧑  作者: Mango

给定一组字符串,找出最长的公共前缀。

例子:

Input  : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}
Output : "gee"

Input  : {"apple", "ape", "april"}
Output : "ap"

我们通过字符匹配算法讨论了词匹配和字符。
在该算法中,讨论了分而治之的方法。我们首先将字符串数组分成两部分。然后我们对左边部分做同样的事情,然后对右边部分做同样的事情。我们将一直这样做,直到并且除非所有字符串的长度都为 1。现在之后,我们将通过返回左右字符串的公共前缀来开始征服。
使用下图可以清楚地了解该算法。我们将我们的字符串视为——“geeksforgeeks”、“geeks”、“geek”、“geezer”。

long_common_prefix6

下面是实现。

C++
//  A C++ Program to find the longest common prefix
#include
using namespace std;
 
// A Utility Function to find the common prefix between
// strings- str1 and str2
string commonPrefixUtil(string str1, string str2)
{
    string result;
    int n1 = str1.length(), n2 = str2.length();
 
    for (int i=0, j=0; i<=n1-1&&j<=n2-1; i++,j++)
    {
        if (str1[i] != str2[j])
            break;
        result.push_back(str1[i]);
    }
    return (result);
}
 
// A Divide and Conquer based function to find the
// longest common prefix. This is similar to the
// merge sort technique
string commonPrefix(string arr[], int low, int high)
{
    if (low == high)
        return (arr[low]);
 
    if (high > low)
    {
        // Same as (low + high)/2, but avoids overflow for
        // large low and high
        int mid = low + (high - low) / 2;
 
        string str1 = commonPrefix(arr, low, mid);
        string str2 = commonPrefix(arr, mid+1, high);
 
        return (commonPrefixUtil(str1, str2));
    }
}
 
// Driver program to test above function
int main()
{
    string arr[] = {"geeksforgeeks", "geeks",
                    "geek", "geezer"};
    int n = sizeof (arr) / sizeof (arr[0]);
 
    string ans = commonPrefix(arr, 0, n-1);
 
    if (ans.length())
        cout << "The longest common prefix is "
             << ans;
    else
        cout << "There is no common prefix";
    return (0);
}


Java
// Java Program to find the longest common prefix
 
class GFG {
 
// A Utility Function to find the common prefix between
// strings- str1 and str2
    static String commonPrefixUtil(String str1, String str2) {
        String result = "";
        int n1 = str1.length(), n2 = str2.length();
 
        for (int i = 0, j = 0; i <= n1 - 1 &&
                j <= n2 - 1; i++, j++) {
            if (str1.charAt(i) != str2.charAt(j)) {
                break;
            }
            result += str1.charAt(i);
        }
        return (result);
    }
 
// A Divide and Conquer based function to find the
// longest common prefix. This is similar to the
// merge sort technique
    static String commonPrefix(String arr[], int low, int high) {
        if (low == high) {
            return (arr[low]);
        }
 
        if (high > low) {
            // Same as (low + high)/2, but avoids overflow for
            // large low and high
            int mid = low + (high - low) / 2;
 
            String str1 = commonPrefix(arr, low, mid);
            String str2 = commonPrefix(arr, mid + 1, high);
 
            return (commonPrefixUtil(str1, str2));
        }
        return null;
    }
 
// Driver program to test above function
    public static void main(String[] args) {
        String arr[] = {"geeksforgeeks", "geeks",
            "geek", "geezer"};
        int n = arr.length;
 
        String ans = commonPrefix(arr, 0, n - 1);
 
        if (ans.length() != 0) {
            System.out.println("The longest common prefix is "
                    + ans);
        } else {
            System.out.println("There is no common prefix");
        }
    }
}
/* This JAVA code is contributed by 29AjayKumar*/


Python3
# A Python3 Program to find the longest common prefix
 
# A Utility Function to find the common
# prefix between strings- str1 and str2
def commonPrefixUtil(str1, str2):
 
    result = ""
    n1, n2 = len(str1), len(str2)
    i, j = 0, 0
 
    while i <= n1 - 1 and j <= n2 - 1:
     
        if str1[i] != str2[j]:
            break
        result += str1[i]
        i, j = i + 1, j + 1
     
    return result
 
# A Divide and Conquer based function to
# find the longest common prefix. This is
# similar to the merge sort technique
def commonPrefix(arr, low, high):
 
    if low == high:
        return arr[low]
 
    if high > low:
     
        # Same as (low + high)/2, but avoids
        # overflow for large low and high
        mid = low + (high - low) // 2
 
        str1 = commonPrefix(arr, low, mid)
        str2 = commonPrefix(arr, mid + 1, high)
 
        return commonPrefixUtil(str1, str2)
 
# Driver Code
if __name__ == "__main__":
 
    arr = ["geeksforgeeks", "geeks",
                   "geek", "geezer"]
    n = len(arr)
    ans = commonPrefix(arr, 0, n - 1)
 
    if len(ans):
        print("The longest common prefix is", ans)
    else:
        print("There is no common prefix")
 
# This code is contributed by Rituraj Jain


C#
// C# Program to find the longest
// common prefix
using System;
 
class GFG
{
// A Utility Function to find
// the common prefix between
// strings- str1 and str2
static string commonPrefixUtil(string str1,
                               string str2)
{
    string result = "";
    int n1 = str1.Length,
        n2 = str2.Length;
 
    for (int i = 0, j = 0;
             i <= n1 - 1 && j <= n2 - 1;
             i++, j++)
    {
        if (str1[i] != str2[j])
            break;
        result += str1[i];
    }
    return (result);
}
 
// A Divide and Conquer based
// function to find the longest
// common prefix. This is similar
// to the merge sort technique
static string commonPrefix(string []arr,
                           int low, int high)
{
    if (low == high)
        return (arr[low]);
 
    if (high > low)
    {
        // Same as (low + high)/2,
        // but avoids overflow for
        // large low and high
        int mid = low + (high - low) / 2;
 
        string str1 = commonPrefix(arr, low, mid);
        string str2 = commonPrefix(arr, mid + 1, high);
 
        return (commonPrefixUtil(str1, str2));
    }
    return null;
}
 
// Driver Code
public static void Main()
{
    String []arr = {"geeksforgeeks", "geeks",
                    "geek", "geezer"};
    int n = arr.Length;
 
    String ans = commonPrefix(arr, 0, n - 1);
 
    if (ans.Length!= 0)
    {
        Console.Write("The longest common " +
                         "prefix is " + ans);
    }
    else
    {
        Console.Write("There is no common prefix");
    }
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出 :

The longest common prefix is gee

时间复杂度:由于我们是通过所有的所有字符串中的字符进行迭代,所以我们可以说,时间复杂度为O(NM),其中,

N = Number of strings
M = Length of the largest string string

辅助空间:为了存储最长的前缀字符串,我们分配了 O(M Log N) 的空间。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程