📌  相关文章
📜  给定数组中没有公共字符的一对字符串的最大长度总和

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

给定数组中没有公共字符的一对字符串的最大长度总和

给定一个由N个字符串组成的数组arr[] ,任务是找到所有唯一对(i, j)的字符串arr[i]arr[j]的最大长度和,其中字符串arr[i]并且arr[j]不包含公共字符。

例子:

朴素方法:解决给定问题的最简单方法是生成所有可能的字符串数组对,并打印它们之间没有公共字符的字符串对的长度之和的最大值。

时间复杂度: O(N 2 * M),其中M字符串的最大长度
辅助空间: O(M)

Efficient Approach:上述方法也可以利用Bit Manipulation的思想进行优化。这个想法是将每个字符串转换为其等效的位掩码整数,然后找到没有公共字符的字符串对,它们的长度之和最大。请按照以下步骤解决问题:

  • 初始化一个大小为N的向量掩码,以将字符串的按位 OR 存储在字符串数组words[] 中。
  • 将变量maxLength初始化为0以存储答案。
  • 使用变量i迭代范围[0, N]并执行以下任务:
    • 使用变量j遍历[0, M]范围,其中M是字符串的长度,并将mask[i]的值设置为mask[i]|1<<(words[i][j] – 'a ')
    • 使用变量j在范围[0, i]上进行迭代,如果mask[i]mask[j]的值按位与不为0 ,则将maxLength的值设置为maxLengthwords[i] 的最大值。长度() + 单词[j].length()
  • 完成上述步骤后,打印maxLength的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the maximum sum of
// length of pair of strings having
// no common characters
int maxSum(vector& words)
{
    // Stores the bitmask of each strings
    vector mask(words.size());
 
    // Initialize the result as zero
    int result = 0;
 
    // Iterate the given vector
    for (int i = 0; i < words.size(); ++i) {
 
        // For each of character
        for (char c : words[i]) {
 
            // If the ith value of
            // mask |= 1 left shift
            // that character - a
            mask[i] |= 1 << (c - 'a');
        }
 
        // Check for each ith character,
        // if the ith and jth value of
        // mask are not same, then add
        // and maximize them
        for (int j = 0; j < i; ++j) {
            if (!(mask[i] & mask[j])) {
                result
                    = max(result, int(words[i].size()
                                      + words[j].size()));
            }
        }
    }
 
    // Return maximum sum of lengths
    // of strings
    return result;
}
 
// Driver Code
int main()
{
    vector words = { "abcd", "def",
                             "fghi", "ijklm" };
    cout << maxSum(words);
 
    return 0;
}


Java
// Java program for the above approach
class GFG {
 
    // Function to find the maximum sum of
    // length of pair of strings having
    // no common characters
    public static int maxSum(String[] words) {
        // Stores the bitmask of each strings
        int[] mask = new int[words.length];
 
        // Initialize the result as zero
        int result = 0;
 
        // Iterate the given vector
        for (int i = 0; i < words.length; ++i) {
 
            // For each of character
            for (char c : words[i].toCharArray()) {
 
                // If the ith value of
                // mask |= 1 left shift
                // that character - a
                mask[i] |= 1 << (c - 'a');
            }
 
            // Check for each ith character,
            // if the ith and jth value of
            // mask are not same, then add
            // and maximize them
            for (int j = 0; j < i; ++j) {
                if ((mask[i] & mask[j]) < 1) {
                    result = Math.max(result, (int) words[i].length() + words[j].length());
                }
            }
        }
 
        // Return maximum sum of lengths
        // of strings
        return result;
    }
 
    // Driver Code
    public static void main(String args[]) {
        String[] words = { "abcd", "def", "fghi", "ijklm" };
        System.out.println(maxSum(words));
 
    }
}
 
// This code is contributed by saurabh_jaiswal.


Python3
# Function to find the maximum sum of
# length of pair of strings having
# no common characters
def maxSum(words):
   
    # Stores the bitmask of each strings
    mask = [0]*len(words)
     
    # Initialize the result as zero
    result = 0
     
        # Iterate the given vector
    for i in range(len(words)):
        for c in words[i]:
           
            # If the ith value of
            # mask |= 1 left shift
            # that character - a
            mask[i] |= 1 << (ord(c)-97)
             
         #  Check for each ith character,
        # if the ith and jth value of
        # mask are not same, then add
        # and maximize them
        for j in range(i):
            if not(mask[i] & mask[j]):
                result = max(result, len(words[i])+len(words[j]))
                 
     # Return maximum sum of lengths
    # of strings           
    return result
 
# Driver code
words = ["abcd", "def", "fghi", "ijklm"]
print(maxSum(words))
 
# This code is contributed by Parth Manchanda


C#
using System;
 
public class GFG {
 
    public static int maxSum(String[] words)
    {
        // Stores the bitmask of each strings
        int[] mask = new int[words.Length];
 
        // Initialize the result as zero
        int result = 0;
 
        // Iterate the given vector
        for (int i = 0; i < words.Length; ++i) {
 
            // For each of character
            foreach  (char c in words[i]) {
               
                // If the ith value of
                // mask |= 1 left shift
                // that character - a
                mask[i] |= 1 << (c - 'a');
            }
 
            // Check for each ith character,
            // if the ith and jth value of
            // mask are not same, then add
            // and maximize them
            for (int j = 0; j < i; ++j) {
                if ((mask[i] & mask[j]) < 1) {
                    result = Math.Max(
                        result, (int)words[i].Length
                                    + words[j].Length);
                }
            }
        }
 
        // Return maximum sum of lengths
        // of strings
        return result;
    }
 
    static public void Main()
    {
        String[] words = { "abcd", "def", "fghi", "ijklm" };
        Console.WriteLine(maxSum(words));
    }
}
 
// This code is contributed by maddler.


Javascript


输出:
9

时间复杂度: O(max(N*M, N 2 )),其中 M 是字符串的最大长度
辅助空间: O(N)