📌  相关文章
📜  从字符串的定Array字符串的总长度使用给定字符组成的

📅  最后修改于: 2021-04-23 17:14:44             🧑  作者: Mango

给定一个字符列表和一个字符串数组,在可以使用给定字符组成的字符串数组中找到所有字符串的总长度。

例子:

方法:

为了解决上述问题,我们必须遵循以下步骤:

  • 我们可以从给定的字符串,是“字符”,而形成一个字符串使用的字符。我们还可以重复使用所使用的字符来形成下一个字符串
  • 通过跟踪字符字符串中每个字符的频率来维护以字符为键和值的无序映射。
  • 每次我们从字符串列表中扫描字符,都会降低无序映射中字符的出现频率,但是我们必须维护原始映射的副本,以便检查第二个字符串。
  • 如果该密钥不存在于映射中,它将创建一个默认值为零的密钥,而不是抛出错误。

下面是上述方法的实现:

C++
// C++ implementation to find total length 
// of string composed of given characters 
// formed from given Array of strings 
  
#include  
using namespace std; 
  
// Function to count the total length 
int countCharacters( 
    vector& strings, 
    string chars) 
{ 
    int res = 0; 
  
    // Unordered_map for 
    // keeping frequency of characters 
    unordered_map freq; 
  
    // Calculate the frequency 
    for (int i = 0; i < chars.length(); i++) 
        freq[chars[i]] += 1; 
  
    // Iterate in the N strings 
    for (auto st : strings) { 
  
        bool flag = true; 
  
        // Iterates in the string 
        for (auto c : st) { 
  
            // Checks if given character of string 
            // string appears in it or not 
            if (!freq) { 
                flag = false; 
                break; 
            } 
        } 
  
        // Adds the length of string 
        // if all characters are present 
        if (flag) 
            res += st.length(); 
    } 
  
    // Return the final result 
    return res; 
} 
  
// Driver code 
int main() 
{ 
    vector strings 
        = { "hi", "data", 
            "geeksforgeeks" }; 
  
    string chars = "tiadhae"; 
  
    cout << countCharacters(strings, chars); 
  
    return 0; 
}


Java
// Java implementation to find total length 
// of string composed of given characters 
// formed from given Array of strings 
import java.util.*; 
class GFG { 
      
// Function to count the total length 
static int countCharacters(List strings, 
                                String chars) 
{ 
    int res = 0; 
  
    // Map for 
    // keeping frequency of characters 
    Map freq = new HashMap<>(); 
  
    // Calculate the frequency 
    for (int i = 0; i < chars.length(); i++) 
    { 
        freq.put(chars.charAt(i), 
        freq.getOrDefault(chars.charAt(i), 0) + 1); 
    } 
  
    // Iterate in the N strings 
    for (String st : strings) 
    { 
        boolean flag = true; 
  
        // Iterates in the string 
        for (char c : st.toCharArray()) 
        { 
  
            // Checks if given character of string 
            // string appears in it or not 
            if (!freq.containsKey(c)) 
            { 
                flag = false; 
                break; 
            } 
        } 
  
        // Adds the length of string 
        // if all characters are present 
        if (flag) 
            res += st.length(); 
    } 
  
    // Return the final result 
    return res; 
} 
  
// Driver code 
public static void main(String[] args) 
{ 
    List strings = Arrays.asList("hi", "data", 
                                        "geeksforgeeks"); 
  
    String chars = "tiadhae"; 
  
    System.out.println(countCharacters(strings, chars)); 
} 
} 
  
// This code is contributed by offbeat


Python3
# Python3 implementation to find total length 
# of string composed of given characters 
# formed from given Array of strings 
  
  
# Function to count the total length 
def countCharacters(arr, chars): 
    res = 0
  
    # Unordered_map for 
    # keeping frequency of characters 
    freq = dict() 
  
    # Calculate the frequency 
    for i in range(len(chars)): 
        freq[chars[i]] = freq.get(chars[i], 0)+1
  
    # Iterate in the N strings 
    for st in arr: 
  
        flag = True
  
        # Iterates in the string 
        for c in st: 
  
            # Checks if given character of string 
            # string appears in it or not 
            if (c not in freq): 
                flag = False
                break
  
        # Adds the length of string 
        # if all characters are present 
        if (flag): 
            res += len(st) 
  
    # Return the final result 
    return res 
  
# Driver code 
if __name__ == '__main__': 
    arr =["hi", "data", "geeksforgeeks"] 
  
    chars = "tiadhae"
  
    print(countCharacters(arr, chars)) 
  
# This code is contributed by mohit kumar 29


C#
// C# implementation to find total length
// of string composed of given characters
// formed from given Array of strings
using System;
using System.Collections.Generic; 
using System.Linq;
  
class GFG{
  
// Function to count the total length
static int countCharacters(List strings, 
                                string chars)
{
    int res = 0;
      
    // Dictionary for keeping frequency
    // of characters
    Dictionary freq = new Dictionary();
      
    // Calculate the frequency
    for(int i = 0; i < chars.Length; i++)
    {
        if(freq.ContainsKey(chars[i]))
        {
            freq[chars[i]]++;
        }
        else
        {
            freq.Add(chars[i], 
                     freq.GetValueOrDefault(
                         chars[i], 0) + 1); 
        }
    }
      
    // Iterate in the N strings
    foreach(string st in strings)
    {
        bool flag = true;
          
        // Iterates in the string
        foreach (char c in st.ToCharArray())
        {
              
            // Checks if given character of string
            // string appears in it or not
            if (!freq.ContainsKey(c)) 
            {
                flag = false;
                break;
            }
        }
          
        // Adds the length of string
        // if all characters are present
        if (flag)
            res += st.Length;
    }
      
    // Return the final result
    return res;
}
  
// Driver code
public static void Main(string[] args)
{
    string []tmp = { "hi", "data", 
                     "geeksforgeeks" };
                       
    List strings = tmp.ToList();
  
    string chars = "tiadhae";
  
    Console.Write(countCharacters(strings, chars));
}
}
  
// This code is contributed by rutvik_56


输出:
6

时间复杂度: O(n * m) ,其中n是char的长度, m是字符串的长度。

辅助空间复杂度: O(1) ,因为无序地图的大小仅为26。