📜  从给定字符串删除频率为素数的字符

📅  最后修改于: 2021-09-04 09:40:28             🧑  作者: Mango

给定长度为N 的字符串str ,任务是从字符串删除频率为素数的所有字符。

例子:

朴素的方法:解决这个问题的最简单的方法是找到 字符串存在的每个不同字符的频率以及每个字符,检查其频率是否为Prime 。如果发现频率为素数,则跳过该字符。否则,将其附加到形成的新字符串。

时间复杂度: O( N 3/2 )
辅助空间: O(N)

高效的方法:可以通过使用 Eratosthenes 筛来预先计算素数来优化上述方法。请按照以下步骤解决问题:

  • 使用Eratosthenes 筛分法,生成最大为N 的所有素数并将它们存储在数组prime[] 中
  • 初始化地图 并存储每个字符的频率。
  • 然后,遍历字符串并借助 map 和 prime[] 数组找出哪些字符具有素数频率
  • 忽略所有具有主要频率的字符并将其余字符存储在一个新字符串。
  • 完成上述步骤后,打印新的字符串。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to perform the seive of
// eratosthenes algorithm
void SieveOfEratosthenes(bool* prime, int n)
{
    // Initialize all entries in
    // prime[] as true
    for (int i = 0; i <= n; i++) {
        prime[i] = true;
    }
 
    // Initialize 0 and 1 as non prime
    prime[0] = prime[1] = false;
 
    // Traversing the prime array
    for (int i = 2; i * i <= n; i++) {
 
        // If i is prime
        if (prime[i] == true) {
 
            // All multiples of i must
            // be marked false as they
            // are non prime
            for (int j = 2; i * j <= n; j++) {
                prime[i * j] = false;
            }
        }
    }
}
 
// Function to remove characters which
// have prime frequency in the string
void removePrimeFrequecies(string s)
{
    // Length of the string
    int n = s.length();
 
    // Create a boolean array prime
    bool prime[n + 1];
 
    // Sieve of Eratosthenes
    SieveOfEratosthenes(prime, n);
 
    // Stores the frequency of character
    unordered_map m;
 
    // Storing the frequecies
    for (int i = 0; i < s.length(); i++) {
        m[s[i]]++;
    }
 
    // New string that will be formed
    string new_string = "";
 
    // Removing the characters which
    // have prime frequencies
    for (int i = 0; i < s.length(); i++) {
 
        // If the character has
        // prime frequency then skip
        if (prime[m[s[i]]])
            continue;
 
        // Else concatenate the
        // character to the new string
        new_string += s[i];
    }
 
    // Print the modified string
    cout << new_string;
}
 
// Driver Code
int main()
{
    string str = "geeksforgeeks";
 
    // Function Call
    removePrimeFrequecies(str);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to perform the seive of
// eratosthenes algorithm
static void SieveOfEratosthenes(boolean[] prime,
                                int n)
{
     
    // Initialize all entries in
    // prime[] as true
    for(int i = 0; i <= n; i++)
    {
        prime[i] = true;
    }
     
    // Initialize 0 and 1 as non prime
    prime[0] = prime[1] = false;
     
    // Traversing the prime array
    for(int i = 2; i * i <= n; i++)
    {
         
        // If i is prime
        if (prime[i] == true)
        {
             
            // All multiples of i must
            // be marked false as they
            // are non prime
            for(int j = 2; i * j <= n; j++)
            {
                prime[i * j] = false;
            }
        }
    }
}
 
// Function to remove characters which
// have prime frequency in the String
static void removePrimeFrequecies(char[] s)
{
     
    // Length of the String
    int n = s.length;
     
    // Create a boolean array prime
    boolean []prime = new boolean[n + 1];
     
    // Sieve of Eratosthenes
    SieveOfEratosthenes(prime, n);
 
    // Stores the frequency of character
    HashMap m = new HashMap<>();
     
    // Storing the frequecies
    for(int i = 0; i < s.length; i++)
    {
        if (m.containsKey(s[i]))
        {
            m.put(s[i], m.get(s[i]) + 1);
        }
        else
        {
            m.put(s[i], 1);
        }
    }
     
    // New String that will be formed
    String new_String = "";
     
    // Removing the characters which
    // have prime frequencies
    for(int i = 0; i < s.length; i++)
    {
         
        // If the character has
        // prime frequency then skip
        if (prime[m.get(s[i])])
            continue;
             
        // Else concatenate the
        // character to the new String
        new_String += s[i];
    }
     
    // Print the modified String
    System.out.print(new_String);
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "geeksforgeeks";
     
    // Function Call
    removePrimeFrequecies(str.toCharArray());
}
}
 
// This code is contributed by aashish1995


Python3
# Python3 program for the above approach
 
# Function to perform the seive of
# eratosthenes algorithm
def SieveOfEratosthenes(prime, n) :
      
    # Initialize all entries in
    # prime[] as true
    for i in range(n + 1) :   
        prime[i] = True
          
    # Initialize 0 and 1 as non prime
    prime[0] = prime[1] = False
      
    # Traversing the prime array
    i = 2
    while i*i <= n :
          
        # If i is prime
        if (prime[i] == True) :
              
            # All multiples of i must
            # be marked false as they
            # are non prime
            j = 2
            while i*j <= n :          
                prime[i * j] = False
                j += 1
        i += 1
         
# Function to remove characters which
# have prime frequency in the String
def removePrimeFrequecies(s) :
      
    # Length of the String
    n = len(s)
      
    # Create a bool array prime
    prime = [False] * (n + 1)
      
    # Sieve of Eratosthenes
    SieveOfEratosthenes(prime, n)
  
    # Stores the frequency of character
    m = {}
      
    # Storing the frequecies
    for i in range(len(s)) :   
        if s[i] in m :       
            m[s[i]]+= 1       
        else :      
            m[s[i]] = 1
      
    # New String that will be formed
    new_String = ""
      
    # Removing the characters which
    # have prime frequencies
    for i in range(len(s)) :
          
        # If the character has
        # prime frequency then skip
        if (prime[m[s[i]]]) :
            continue
              
        # Else concatenate the
        # character to the new String
        new_String += s[i]
      
    # Print the modified String
    print(new_String, end = "")
     
Str = "geeksforgeeks"
      
# Function Call
removePrimeFrequecies(list(Str))
 
# This code is contributed by divyesh072019


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to perform the seive of
// eratosthenes algorithm
static void SieveOfEratosthenes(bool[] prime,
                                int n)
{
     
    // Initialize all entries in
    // prime[] as true
    for(int i = 0; i <= n; i++)
    {
        prime[i] = true;
    }
     
    // Initialize 0 and 1 as non prime
    prime[0] = prime[1] = false;
     
    // Traversing the prime array
    for(int i = 2; i * i <= n; i++)
    {
         
        // If i is prime
        if (prime[i] == true)
        {
             
            // All multiples of i must
            // be marked false as they
            // are non prime
            for(int j = 2; i * j <= n; j++)
            {
                prime[i * j] = false;
            }
        }
    }
}
 
// Function to remove characters which
// have prime frequency in the String
static void removePrimeFrequecies(char[] s)
{
     
    // Length of the String
    int n = s.Length;
     
    // Create a bool array prime
    bool []prime = new bool[n + 1];
     
    // Sieve of Eratosthenes
    SieveOfEratosthenes(prime, n);
 
    // Stores the frequency of character
    Dictionary m = new Dictionary();
     
    // Storing the frequecies
    for(int i = 0; i < s.Length; i++)
    {
        if (m.ContainsKey(s[i]))
        {
            m[s[i]]++;
        }
        else
        {
            m.Add(s[i], 1);
        }
    }
     
    // New String that will be formed
    String new_String = "";
     
    // Removing the characters which
    // have prime frequencies
    for(int i = 0; i < s.Length; i++)
    {
         
        // If the character has
        // prime frequency then skip
        if (prime[m[s[i]]])
            continue;
             
        // Else concatenate the
        // character to the new String
        new_String += s[i];
    }
     
    // Print the modified String
    Console.Write(new_String);
}
 
// Driver Code
public static void Main(String[] args)
{
    String str = "geeksforgeeks";
     
    // Function Call
    removePrimeFrequecies(str.ToCharArray());
}
}
 
// This code is contributed by aashish1995


输出:
eeforee

时间复杂度: O(N*log (log N))
辅助空间: O(N)

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