📌  相关文章
📜  使用逐字匹配的最长公共前缀

📅  最后修改于: 2022-05-13 01:57:08.094000             🧑  作者: Mango

使用逐字匹配的最长公共前缀

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

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

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

我们从一个例子开始。假设有两个字符串——“geeksforgeeks”和“geeks”。两者中最长的公共前缀是什么?是“极客”。
现在让我们介绍另一个词“极客”。那么现在这三个词中最长的公共前缀是什么?这是“极客”
我们可以看到最长的公共前缀具有关联属性,即-

LCP(string1, string2, string3) 
         = LCP (LCP (string1, string2), string3)

Like here

LCP (“geeksforgeeks”, “geeks”, “geek”)
     =  LCP (LCP (“geeksforgeeks”, “geeks”), “geek”)
     =  LCP (“geeks”, “geek”) = “geek”

所以我们可以利用上面的关联属性来找到给定字符串的 LCP。我们用到目前为止的LCP一一计算每个给定字符串的LCP。最终结果将是我们所有字符串中最长的公共前缀。
请注意,给定的字符串可能没有公共前缀。当所有字符串的第一个字符不相同时,就会发生这种情况。
我们通过下图展示了带有输入字符串的算法 - “geeksforgeeks”、“geeks”、“geek”、“geezer”。

最长的公共前缀

以下是上述方法的实现:

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();
 
    // Compare str1 and str2
    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 Function that returns the longest common prefix
// from the array of strings
string commonPrefix (string arr[], int n)
{
    string prefix =  arr[0];
 
    for (int i=1; i<=n-1; i++)
        prefix = commonPrefixUtil(prefix, arr[i]);
 
    return (prefix);
}
 
// 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, n);
 
    if (ans.length())
        printf ("The longest common prefix is - %s",
                 ans.c_str());
    else
        printf("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();
 
        // Compare str1 and str2
        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 Function that returns the longest common prefix
// from the array of strings
    static String commonPrefix(String arr[], int n) {
        String prefix = arr[0];
 
        for (int i = 1; i <= n - 1; i++) {
            prefix = commonPrefixUtil(prefix, arr[i]);
        }
 
        return (prefix);
    }
 
// 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, n);
 
        if (ans.length() > 0) {
            System.out.printf("The longest common prefix is - %s",
                    ans);
        } else {
            System.out.printf("There is no common prefix");
        }
    }
}
// This 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 = len(str1)
    n2 = len(str2)
 
    # Compare str1 and str2
    i = 0
    j = 0
    while i <= n1 - 1 and j <= n2 - 1:
     
        if (str1[i] != str2[j]):
            break
             
        result += str1[i]
        i += 1
        j += 1
 
    return (result)
 
# A Function that returns the longest
# common prefix from the array of strings
def commonPrefix (arr, n):
 
    prefix = arr[0]
 
    for i in range (1, n):
        prefix = commonPrefixUtil(prefix, arr[i])
 
    return (prefix)
 
# Driver Code
if __name__ =="__main__":
 
    arr = ["geeksforgeeks", "geeks",
                    "geek", "geezer"]
    n = len(arr)
 
    ans = commonPrefix(arr, n)
 
    if (len(ans)):
        print ("The longest common prefix is -",
                ans);
    else:
        print("There is no common prefix")
 
# This code is contributed by ita_c


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;
 
    // Compare str1 and str2
    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 Function that returns the longest
// common prefix from the array of strings
static String commonPrefix(String []arr, int n)
{
    String prefix = arr[0];
 
    for (int i = 1; i <= n - 1; i++)
    {
        prefix = commonPrefixUtil(prefix,
                     arr.GetValue(i).ToString());
    }
 
    return (prefix);
}
 
// Driver Code
public static void Main()
{
    String []arr = {"geeksforgeeks", "geeks",
                    "geek", "geezer"};
    int n = arr.Length;
 
    String ans = commonPrefix(arr, n);
 
    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