📌  相关文章
📜  两个数组中满足给定条件的字符串数

📅  最后修改于: 2021-09-03 04:02:34             🧑  作者: Mango

给定两个字符串数组arr1[]arr2[] 。对于arr2[] (比如str2 )中的每个字符串,任务是计算arr1[] (比如str1 )中满足以下条件的数字字符串:

  • str1str2的第一个字符必须相等。
  • 字符串str2必须包含字符串str1 的每个字符。

例子:

方法:这个问题可以使用Bitmasking的概念来解决。以下是步骤:

  • 将数组arr1[] 的每个字符串转换为其对应的位掩码,如下所示:
For string str = "abcd"
the corresponding bitmask conversion is:
characters | value 
    a          0
    b          1
    c          2
    d          3
As per the above characters value, the number is:
value = 20 + 21 + 23 + 24
value = 15.
so the string "abcd" represented as 15.
  • 注意:当对每个字符串掩码时,如果字符的频率大于 1,则只包含一次相应的字符。
  • 将每个字符串的频率存储在 unordered_map 中。
  • 同样,将arr2[]中的每个字符串转换为相应的位掩码并执行以下操作:
    • 不是计算对应于arr1[] 的所有可能的单词,而是使用位运算使用temp = (temp – 1)&val来查找下一个有效位掩码。
    • 它产生下一个位掩码模式,通过产生所有可能的组合一次减少一个字符。
  • 对于每个有效的排列,检查它是否验证给定的两个条件并将相应的频率添加到存储在 unordered_map 中的当前字符串到结果中。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
void findNumOfValidWords(vector& w,
                         vector& p)
{
    // To store the frequency of string
    // after bitmasking
    unordered_map m;
 
    // To store result for each string
    // in arr2[]
    vector res;
 
    // Traverse the arr1[] and bitmask each
    // string in it
    for (string& s : w) {
 
        int val = 0;
 
        // Bitmasking for each string s
        for (char c : s) {
            val = val | (1 << (c - 'a'));
        }
 
        // Update the frequency of string
        // with it's bitmasking value
        m[val]++;
    }
 
    // Traverse the arr2[]
    for (string& s : p) {
        int val = 0;
 
        // Bitmasking for each string s
        for (char c : s) {
            val = val | (1 << (c - 'a'));
        }
 
        int temp = val;
        int first = s[0] - 'a';
        int count = 0;
 
        while (temp != 0) {
 
            // Check if temp is present
            // in an unordered_map or not
            if (((temp >> first) & 1) == 1) {
                if (m.find(temp) != m.end()) {
                    count += m[temp];
                }
            }
 
            // Check for next set bit
            temp = (temp - 1) & val;
        }
 
        // Push the count for current
        // string in resultant array
        res.push_back(count);
    }
 
    // Print the count for each string
    for (auto& it : res) {
        cout << it << '\n';
    }
}
 
// Driver Code
int main()
{
    vector arr1;
    arr1 = { "aaaa", "asas", "able",
             "ability", "actt",
             "actor", "access" };
 
    vector arr2;
    arr2 = { "aboveyz", "abrodyz",
             "abslute", "absoryz",
             "actresz", "gaswxyz" };
 
    // Function call
    findNumOfValidWords(arr1, arr2);
    return 0;
}


Java
// Java program for
// the above approach
import java.util.*;
class GFG{
 
static void findNumOfValidWords(Vector w,
                                Vector p)
{
  // To store the frequency of String
  // after bitmasking
  HashMap m = new HashMap<>();
 
  // To store result for
  // each string in arr2[]
  Vector res = new Vector<>();
 
  // Traverse the arr1[] and
  // bitmask each string in it
  for (String s : w)
  {
    int val = 0;
 
    // Bitmasking for each String s
    for (char c : s.toCharArray())
    {
      val = val | (1 << (c - 'a'));
    }
 
    // Update the frequency of String
    // with it's bitmasking value
    if(m.containsKey(val))
      m.put(val, m.get(val) + 1);
    else
      m.put(val, 1);
  }
 
  // Traverse the arr2[]
  for (String s : p)
  {
    int val = 0;
 
    // Bitmasking for each String s
    for (char c : s.toCharArray())
    {
      val = val | (1 << (c - 'a'));
    }
 
    int temp = val;
    int first = s.charAt(0) - 'a';
    int count = 0;
 
    while (temp != 0)
    {
      // Check if temp is present
      // in an unordered_map or not
      if (((temp >> first) & 1) == 1)
      {
        if (m.containsKey(temp))
        {
          count += m.get(temp);
        }
      }
 
      // Check for next set bit
      temp = (temp - 1) & val;
    }
 
    // Push the count for current
    // String in resultant array
    res.add(count);
  }
 
  // Print the count for each String
  for (int it : res)
  {
    System.out.println(it);
  }
}
 
// Driver Code
public static void main(String[] args)
{
  Vector arr1 = new Vector<>();
  arr1.add("aaaa"); arr1.add("asas");
  arr1.add("able"); arr1.add("ability");
  arr1.add("actt"); arr1.add("actor");
  arr1.add("access");
 
  Vector arr2 = new Vector<>();
  arr2.add("aboveyz"); arr2.add("abrodyz");
  arr2.add("abslute"); arr2.add("absoryz");
  arr2.add("actresz"); arr2.add("gaswxyz");
 
  // Function call
  findNumOfValidWords(arr1, arr2);
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 program for the above approach
from collections import defaultdict
 
def findNumOfValidWords(w, p):
 
    # To store the frequency of string
    # after bitmasking
    m = defaultdict(int)
 
    # To store result for each string
    # in arr2[]
    res = []
 
    # Traverse the arr1[] and bitmask each
    # string in it
    for s in w:
        val = 0
 
        # Bitmasking for each string s
        for c in s:
            val = val | (1 << (ord(c) - ord('a')))
 
        # Update the frequency of string
        # with it's bitmasking value
        m[val] += 1
 
    # Traverse the arr2[]
    for s in p:
        val = 0
 
        # Bitmasking for each string s
        for c in s:
            val = val | (1 << (ord(c) - ord('a')))
 
        temp = val
        first = ord(s[0]) - ord('a')
        count = 0
         
        while (temp != 0):
 
            # Check if temp is present
            # in an unordered_map or not
            if (((temp >> first) & 1) == 1):
                if (temp in m):
                    count += m[temp]
 
            # Check for next set bit
            temp = (temp - 1) & val
 
        # Push the count for current
        # string in resultant array
        res.append(count)
     
    # Print the count for each string
    for it in res:
        print(it)
 
# Driver Code
if __name__ == "__main__":
 
    arr1 = [ "aaaa", "asas", "able",
             "ability", "actt",
             "actor", "access" ]
 
    arr2 = [ "aboveyz", "abrodyz",
             "abslute", "absoryz",
             "actresz", "gaswxyz" ]
 
    # Function call
    findNumOfValidWords(arr1, arr2)
 
# This code is contributed by chitranayal


C#
// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
static void findNumOfValidWords(List w,
                                List p)
{
  // To store the frequency of String
  // after bitmasking
  Dictionary m = new Dictionary();
   
  // To store result for
  // each string in arr2[]
  List res = new List();
 
  // Traverse the arr1[] and
  // bitmask each string in it
  foreach (String s in w)
  {
    int val = 0;
 
    // Bitmasking for each String s
    foreach (char c in s.ToCharArray())
    {
      val = val | (1 << (c - 'a'));
    }
 
    // Update the frequency of String
    // with it's bitmasking value
    if(m.ContainsKey(val))
      m[val] = m[val] + 1;
    else
      m.Add(val, 1);
  }
 
  // Traverse the arr2[]
  foreach (String s in p)
  {
    int val = 0;
 
    // Bitmasking for each String s
    foreach (char c in s.ToCharArray())
    {
      val = val | (1 << (c - 'a'));
    }
 
    int temp = val;
    int first = s[0] - 'a';
    int count = 0;
 
    while (temp != 0)
    {
      // Check if temp is present
      // in an unordered_map or not
      if (((temp >> first) & 1) == 1)
      {
        if (m.ContainsKey(temp))
        {
          count += m[temp];
        }
      }
 
      // Check for next set bit
      temp = (temp - 1) & val;
    }
 
    // Push the count for current
    // String in resultant array
    res.Add(count);
  }
 
  // Print the count
  // for each String
  foreach (int it in res)
  {
    Console.WriteLine(it);
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  List arr1 = new List();
  arr1.Add("aaaa"); arr1.Add("asas");
  arr1.Add("able"); arr1.Add("ability");
  arr1.Add("actt"); arr1.Add("actor");
  arr1.Add("access");
 
  List arr2 = new List();
  arr2.Add("aboveyz"); arr2.Add("abrodyz");
  arr2.Add("abslute"); arr2.Add("absoryz");
  arr2.Add("actresz"); arr2.Add("gaswxyz");
 
  // Function call
  findNumOfValidWords(arr1, arr2);
}
}
 
// This code is contributed by shikhasingrajput


Javascript


输出:
1
1
3
2
4
0

时间复杂度: O(N)
空间复杂度: O(N)

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