📌  相关文章
📜  通过重新排列给定数组中的字符串,可能的最长公共前缀长度

📅  最后修改于: 2021-09-03 03:43:49             🧑  作者: Mango

给定一个字符串数组arr[] ,任务是通过重新排列给定数组中每个字符串的字符来找到最长公共前缀的长度。

例子:

朴素的方法:解决这个问题的最简单的方法是生成给定数组的每个字符串的所有可能排列,并找到所有字符串的最长公共前缀。最后,打印最长公共前缀的长度。

时间复杂度: O(N * log M * (M!) N )
辅助空间: O(M),N是字符串的个数,M是最长字符串的长度。

高效的方法:优化上述方法的想法是使用哈希。请按照以下步骤解决问题:

  • 初始化一个二维数组,比如freq[N][256]使得freq[i][j]将字符(= j)的频率存储在字符串arr[i] 中
  • 遍历给定数组并将arr[i][j]的频率存储到freq[i][arr[i][j]] 中
  • 初始化一个变量,比如maxLen来存储最长公共前缀的长度
  • 遍历所有可能的字符和发现的最小频率,说在给定数组的所有字符串当前字符的minRowVal,并增加由minRowValMAXLEN的值
  • 最后,打印maxLen的值。

下面是上述方法的实现:

C++14
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to get the length
// of the longest common prefix
// by rearranging the strings
int longComPre(string arr[], int N)
{
    // freq[i][j]: stores the frequency
    // of a character(= j) in
    // a string arr[i]
    int freq[N][256];
 
    // Initilize freq[][] array.
    memset(freq, 0, sizeof(freq));
 
    // Traverse the given array
    for (int i = 0; i < N; i++) {
 
        // Stores length of
        // current string
        int M = arr[i].length();
 
        // Traverse current string
        // of the given array
        for (int j = 0; j < M;
             j++) {
 
            // Update the value of
            // freq[i][arr[i][j]]
            freq[i][arr[i][j]]++;
        }
    }
 
    // Stores the length of
    // longest common prefix
    int maxLen = 0;
 
    // Count the minimum frequency
    // of each character in
    // in all the strings of arr[]
    for (int j = 0; j < 256; j++) {
 
        // Stores minimum value
        // in each row of freq[][]
        int minRowVal = INT_MAX;
 
        // Calculate minimum frequency
        // of current character
        // in all the strings.
        for (int i = 0; i < N;
             i++) {
 
            // Update minRowVal
            minRowVal = min(minRowVal,
                            freq[i][j]);
        }
 
        // Update maxLen
        maxLen += minRowVal;
    }
    return maxLen;
}
 
// Driver Code
int main()
{
    string arr[] = { "aabdc",
                     "abcd",
                     "aacd" };
    int N = 3;
    cout << longComPre(arr, N);
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to get the length
// of the longest common prefix
// by rearranging the Strings
static int longComPre(String arr[],
                      int N)
{
  // freq[i][j]: stores the
  // frequency of a character(= j)
  // in a String arr[i]
  int [][]freq = new int[N][256];
 
  // Traverse the given array
  for (int i = 0; i < N; i++)
  {
    // Stores length of
    // current String
    int M = arr[i].length();
 
    // Traverse current String
    // of the given array
    for (int j = 0; j < M; j++)
    {
      // Update the value of
      // freq[i][arr[i][j]]
      freq[i][arr[i].charAt(j)]++;
    }
  }
 
  // Stores the length of
  // longest common prefix
  int maxLen = 0;
 
  // Count the minimum frequency
  // of each character in
  // in all the Strings of arr[]
  for (int j = 0; j < 256; j++)
  {
    // Stores minimum value
    // in each row of freq[][]
    int minRowVal = Integer.MAX_VALUE;
 
    // Calculate minimum frequency
    // of current character
    // in all the Strings.
    for (int i = 0; i < N; i++)
    {
      // Update minRowVal
      minRowVal = Math.min(minRowVal,
                           freq[i][j]);
    }
 
    // Update maxLen
    maxLen += minRowVal;
  }
  return maxLen;
}
 
// Driver Code
public static void main(String[] args)
{
  String arr[] = {"aabdc",
                  "abcd",
                  "aacd"};
  int N = 3;
  System.out.print(longComPre(arr, N));
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program to implement
# the above approach
import sys
 
# Function to get the length
# of the longest common prefix
# by rearranging the strings
def longComPre(arr, N):
     
    # freq[i][j]: stores the frequency
    # of a character(= j) in
    # a arr[i]
    freq = [[0 for i in range(256)]
               for i in range(N)]
 
    # Initialize freq[][] array.
    # memset(freq, 0, sizeof(freq))
 
    # Traverse the given array
    for i in range(N):
         
        # Stores length of
        # current string
        M = len(arr[i])
 
        # Traverse current string
        # of the given array
        for j in range(M):
             
            # Update the value of
            # freq[i][arr[i][j]]
            freq[i][ord(arr[i][j])] += 1
 
    # Stores the length of
    # longest common prefix
    maxLen = 0
 
    # Count the minimum frequency
    # of each character in
    #in all the strings of arr[]
    for j in range(256):
         
        # Stores minimum value
        # in each row of freq[][]
        minRowVal = sys.maxsize
 
        # Calculate minimum frequency
        # of current character
        # in all the strings.
        for i in range(N):
             
            # Update minRowVal
            minRowVal = min(minRowVal,
                            freq[i][j])
 
        # Update maxLen
        maxLen += minRowVal
         
    return maxLen
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ "aabdc", "abcd", "aacd" ]
    N = 3
     
    print(longComPre(arr, N))
 
# This code is contributed by mohit kumar 29


C#
// C# program to implement
// the above approach
using System;
class GFG{
 
// Function to get the length
// of the longest common prefix
// by rearranging the Strings
static int longComPre(String []arr,
                      int N)
{
  // freq[i,j]: stores the
  // frequency of a character(= j)
  // in a String arr[i]
  int [,]freq = new int[N, 256];
 
  // Traverse the given array
  for (int i = 0; i < N; i++)
  {
    // Stores length of
    // current String
    int M = arr[i].Length;
 
    // Traverse current String
    // of the given array
    for (int j = 0; j < M; j++)
    {
      // Update the value of
      // freq[i,arr[i,j]]
      freq[i, arr[i][j]]++;
    }
  }
 
  // Stores the length of
  // longest common prefix
  int maxLen = 0;
 
  // Count the minimum frequency
  // of each character in
  // in all the Strings of []arr
  for (int j = 0; j < 256; j++)
  {
    // Stores minimum value
    // in each row of [,]freq
    int minRowVal = int.MaxValue;
 
    // Calculate minimum frequency
    // of current character
    // in all the Strings.
    for (int i = 0; i < N; i++)
    {
      // Update minRowVal
      minRowVal = Math.Min(minRowVal,
                           freq[i, j]);
    }
 
    // Update maxLen
    maxLen += minRowVal;
  }
  return maxLen;
}
 
// Driver Code
public static void Main(String[] args)
{
  String []arr = {"aabdc",
                  "abcd",
                  "aacd"};
  int N = 3;
  Console.Write(longComPre(arr, N));
}
}
 
// This code is contributed by gauravrajput1


输出
3


时间复杂度: O(N * (M + 256))
辅助空间: O(N * 256)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live