📜  检查字符串中不同字符的计数是否为质数

📅  最后修改于: 2021-05-31 23:22:40             🧑  作者: Mango

给定字符串小写英文字母。任务是检查字符串中不同字符的计数是否为质数。
例子:

Input : str = "geeksforgeeks"
Output :Yes
Explanation: The number of distinct characters in the
string is 7, and 7 is a prime number.

Input : str ="geeks"
Output : No 

在这个问题中,首先我们必须计算字符串的不同字符。我们将使用地图存储每个字母的频率。下一步是计算不同字符的数量,并检查数字是否为质数。
如果数字是素数,我们将打印“是”,否则打印“否”。
下面是上述方法的实现:

C++
// C++ program to check whether count of
// distinct characters in a string
// is Prime or not
#include 
using namespace std;
 
// Find whether a number is prime or not
bool isPrime(int n)
{
    int i;
 
    // 1 is not prime
    if (n == 1)
        return false;
 
    // check if there is any factor or not
    for (i = 2; i <= sqrt(n); i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}
 
// Count the distinct characters in a string
int countDistinct(string s)
{
    // create a map to store the
    // frequency of characters
    unordered_map m;
 
    // traverse the string
    for (int i = 0; i < s.length(); i++) {
        // increase the frequency of character
        m[s[i]]++;
    }
 
    return m.size();
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
 
    if (isPrime(countDistinct(str)))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
 
    return 0;
}


Java
// Java program to check whether count of
// distinct characters in a string
// is Prime or not
import java.util.*;
 
class GFG
{
    // Find whether a number is prime or not
    static boolean isPrime(int n)
    {
        int i;
     
        // 1 is not prime
        if (n == 1)
            return false;
     
        // check if there is any factor or not
        for (i = 2; i <= Math.sqrt(n); i++)
        {
            if (n % i == 0)
                return false;
        }
        return true;
    }
     
    // Count the distinct characters in a string
    static int countDistinct(String s)
    {
        // create a map to store the
        // frequency of characters
        Set m = new HashSet();
     
        // traverse the string
        for (int i = 0; i < s.length(); i++)
        {
             
            // increase the frequency of character
            m.add(s.charAt(i));
             
        }
         
        return m.size();
    }
     
    // Driver code
    public static void main(String []args)
    {
        String str = "geeksforgeeks";
     
        if (isPrime(countDistinct(str)))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by ihritik


Python 3
# Python 3 program to check whether
# count of distinct characters in a
# string is Prime or not
 
# from math library import
# sqrt method
from math import sqrt
 
# Find whether a number
# is prime or not
def isPrime(n) :
 
    # 1 is not prime
    if n == 1 :
        return False
 
    # check if there is any
    # factor or not
    for i in range(2, int(sqrt(n)) + 1) :
 
        if n % i == 0 :
            return False
 
    return True
 
# Count the distinct characters
# in a string
def countDistinct(s) :
 
    # create a dictionary to store
    # the frequency of characters
    m = {}
 
    # dictionary with keys and its
    # initialize with value 0
    m = m.fromkeys(s, 0)
 
    # traverse the string
    for i in range(len(s)) :
 
        # increase the frequency
        # of character
        m[s[i]] += 1
 
    return len(m.keys())
 
# Driver code    
if __name__ == "__main__" :
 
    str = "geeksforgeeks"
 
    if isPrime(countDistinct(str)) :
        print("Yes")
    else :
        print("No")
         
# This code is contributed
# by ANKITRAI1


C#
// C# program to check whether count of
// distinct characters in a string
// is Prime or not
using System;
using System.Collections.Generic;
 
class GFG
{
    // Find whether a number is prime or not
    static bool isPrime(int n)
    {
        int i;
     
        // 1 is not prime
        if (n == 1)
            return false;
     
        // check if there is any factor or not
        for (i = 2; i <= Math.Sqrt(n); i++)
        {
            if (n % i == 0)
                return false;
        }
        return true;
    }
     
    // Count the distinct characters in a string
    static int countDistinct(String s)
    {
        // create a map to store the
        // frequency of characters
        HashSet m = new HashSet();
     
        // traverse the string
        for (int i = 0; i < s.Length; i++)
        {
             
            // increase the frequency of character
            m.Add(s[i]);
             
        }
         
        return m.Count;
    }
     
    // Driver code
    public static void Main(String []args)
    {
        String str = "geeksforgeeks";
     
        if (isPrime(countDistinct(str)))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript


Python3
# Python program for the above approach
from collections import Counter
from math import sqrt as sqrt
 
 
def isPrime(n):
 
    # 1 is not prime
    if n == 1:
        return False
 
    # check if there is any
    # factor or not
    for i in range(2, int(sqrt(n)) + 1):
 
        if n % i == 0:
            return False
 
    return True
 
# Function to count the number of distinct
# characters present in the string
# str and check whether it is prime
def countDis(str):
 
    # Stores all frquencies
    freq = Counter(str)
 
    # Return the size of the freq dictionary
    if(isPrime(len(freq))):
        return True
    else:
        return False
 
 
# Driver Code
if __name__ == "__main__":
 
        # Given string S
    S = "geeksforgeeks"
 
    print(countDis(S))
 
# This code is contributed by vikkycirus


输出:
Yes

时间复杂度: O((len(str)) 1/2 )

辅助空间: O(len(str))

方法2:使用计数器函数:

  1. 使用计数器函数对所有元素的频率进行计数,该频率词典的键数给出计数并检查其是否为质数。

下面是实现:

Python3

# Python program for the above approach
from collections import Counter
from math import sqrt as sqrt
 
 
def isPrime(n):
 
    # 1 is not prime
    if n == 1:
        return False
 
    # check if there is any
    # factor or not
    for i in range(2, int(sqrt(n)) + 1):
 
        if n % i == 0:
            return False
 
    return True
 
# Function to count the number of distinct
# characters present in the string
# str and check whether it is prime
def countDis(str):
 
    # Stores all frquencies
    freq = Counter(str)
 
    # Return the size of the freq dictionary
    if(isPrime(len(freq))):
        return True
    else:
        return False
 
 
# Driver Code
if __name__ == "__main__":
 
        # Given string S
    S = "geeksforgeeks"
 
    print(countDis(S))
 
# This code is contributed by vikkycirus

输出:

True
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”