📜  使用字符字符的最长公共前缀

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

使用字符字符的最长公共前缀

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

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

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

我们在上一篇文章中讨论了逐字匹配算法。
在这个算法中,我们不是一个一个地遍历字符串,而是一个一个地遍历字符。
我们将我们的字符串视为 – “geeksforgeeks”、“geeks”、“geek”、“geezer”。

最长的公共前缀2

最长的公共前缀3

最长的公共前缀4

最长的公共前缀5

下面是这种方法的实现。

C++
//  A C++ Program to find the longest common prefix
#include
using namespace std;
 
// A Function to find the string having the minimum
// length and returns that length
int findMinLength(string arr[], int n)
{
    int min = arr[0].length();
 
    for (int i=1; i


Java
// A Java Program to find the longest common prefix
class GFG
{
 
    // A Function to find the string having the minimum
    // length and returns that length
    static int findMinLength(String arr[], int n)
    {
        int min = arr[0].length();
 
        for (int i = 1; i < n; i++)
        {
            if (arr[i].length() < min)
            {
                min = arr[i].length();
            }
        }
 
        return (min);
    }
 
    // A Function that returns the longest common prefix
    // from the array of strings
    static String commonPrefix(String arr[], int n)
    {
        int minlen = findMinLength(arr, n);
 
        String result = ""; // Our resultant string
        char current; // The current character
 
        for (int i = 0; i < minlen; i++)
        {
            // Current character (must be same
            // in all strings to be a part of
            // result)
            current = arr[0].charAt(i);
 
            for (int j = 1; j < n; j++)
            {
                if (arr[j].charAt(i) != current)
                {
                    return result;
                }
            }
 
            // Append to result
            result += (current);
        }
 
        return (result);
    }
 
    // 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.println("The longest common prefix is "
                    + ans);
        } else {
            System.out.println("There is no common prefix");
        }
    }
}
 
// This code contributed by Rajput-Ji


Python 3
# Python 3 Program to find the longest common prefix
  
# A Function to find the string having the minimum
# length and returns that length
def findMinLength(arr, n):
 
    min = len(arr[0])
  
    for i in range(1,n):
        if (len(arr[i])< min):
            min = len(arr[i])
  
    return(min)
  
# A Function that returns the longest common prefix
# from the array of strings
def commonPrefix(arr, n):
 
    minlen = findMinLength(arr, n)
    result =""
    for i in range(minlen):
     
        # Current character (must be same
        # in all strings to be a part of
        # result)
        current = arr[0][i]
  
        for j in range(1,n):
            if (arr[j][i] != current):
                return result
  
        # Append to result
        result = result+current
  
    return (result)
  
# Driver program to test above function
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")


C#
// A C# Program to find the longest common prefix
using System;
     
class GFG
{
 
    // A Function to find the string having the minimum
    // length and returns that length
    static int findMinLength(String []arr, int n)
    {
        int min = arr[0].Length;
 
        for (int i = 1; i < n; i++)
        {
            if (arr[i].Length < min)
            {
                min = arr[i].Length;
            }
        }
 
        return (min);
    }
 
    // A Function that returns the longest common prefix
    // from the array of strings
    static String commonPrefix(String []arr, int n)
    {
        int minlen = findMinLength(arr, n);
 
        String result = ""; // Our resultant string
        char current; // The current character
 
        for (int i = 0; i < minlen; i++)
        {
            // Current character (must be same
            // in all strings to be a part of
            // result)
            current = arr[0][i];
 
            for (int j = 1; j < n; j++)
            {
                if (arr[j][i] != current)
                {
                    return result;
                }
            }
 
            // Append to result
            result += (current);
        }
 
        return (result);
    }
 
    // Driver code
    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)
        {
            Console.WriteLine("The longest common prefix is "
                    + ans);
        }
        else
        {
            Console.WriteLine("There is no common prefix");
        }
    }
}
 
/* This code contributed by PrinciRaj1992 */


Javascript


输出 :

The longest common prefix is  gee

这个算法比“逐字匹配”算法好多少?-
在第 1 组中,我们讨论了“逐字匹配”算法。
假设您的输入字符串为“geeksforgeeks”、“geeks”、“geek”、“geezer”、“x”。
现在没有上述字符串的公共前缀字符串。通过 Set 1 中讨论的“逐字匹配”算法,我们通过遍历所有字符串得出没有公共前缀字符串的结论。但是如果我们使用这个算法,那么在第一次迭代中我们就会知道没有公共前缀字符串 ,因为我们不会进一步寻找每个字符串的第二个字符。
当字符串太多时,这种算法有很大的优势。
时间复杂度:由于我们正在遍历所有字符的所有字符串,所以我们可以说时间复杂度是 O(NM) 其中,

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