📌  相关文章
📜  检查是否可以通过从 S1 中添加或删除字符来获得 S2 的排列

📅  最后修改于: 2021-10-27 17:08:13             🧑  作者: Mango

给定两个字符串S1S2选自NM字符,则任务是检查如果字符串S1可以在添加或从字符串S1去除的字符的次一个素数后做成等于S2的任何排列。如果可能,则打印“是” 。否则,打印“否”

例子:

方法:给定的问题可以通过计算字符串S1S2中字符的频率来解决,如果任何字符的频率差异不是素数,则打印“否” 。否则,打印“是” 。请按照以下步骤解决问题:

  • 初始化频率数组,比如大小为256 的freq[]
  • 迭代字符串S1的字符和为每个字符减1字符的频率在频率[]。
  • 迭代字符串S2的字符和为每个字符递增1字符的频率在频率[]。
  • 完成上述步骤后,如果freq[]中所有元素的绝对值都是素数,则打印“Yes” 。否则,打印“否”

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if the given
// number is prime or not
bool isPrime(int n)
{
     
    // If the number is less than 2
    if (n <= 1)
        return false;
 
    // If the number is 2
    else if (n == 2)
        return true;
 
    // If N is a multiple of 2
    else if (n % 2 == 0)
        return false;
 
    // Otherwise, check for the
    // odds values
    for(int i = 3;i <= sqrt(n); i += 2)
    {
        if (n % i == 0)
            return false;
    }
    return true;
}
 
// Function to check if S1 can be
// a permutation of S2 by adding
// or removing characters from S1
void checkPermutation(string s1, string s2)
{
     
    // Initialize a frequency array
    int freq[26] = {0};
     
    // Decrement the frequency for
    // occurrence in s1
    for(char ch : s1)
    {
        freq[ch - 'a']--;
    }
 
    // Increment the frequency for
    // occurence in s2
    for(char ch : s2)
    {
        freq[ch - 'a']++;
    }
 
    bool isAllChangesPrime = true;
 
    for(int i = 0; i < 26; i++)
    {
         
        // If frequency of current
        // char is same in s1 and s2
        if (freq[i] == 0)
        {
            continue;
        }
 
        // Check the frequency for
        // the current char is not
        // prime
        else if (!isPrime(abs(freq[i])))
        {
            isAllChangesPrime = false;
            break;
        }
    }
 
    // Print the result
    if (isAllChangesPrime)
    {
        cout << "Yes";
    }
    else
    {
        cout << "No";
    }
}
 
// Driver Code
int main()
{
    string S1 = "gekforgk";
    string S2 = "geeksforgeeks";
     
    checkPermutation(S1, S2);
}
 
// This code is contributed by mohit kumar 29


Java
// Java program for the above approach
 
public class GFG {
 
    // Function to check if the given
    // number is prime or not
    private static boolean isPrime(int n)
    {
        // If the number is less than 2
        if (n <= 1)
            return false;
 
        // If the number is 2
        else if (n == 2)
            return true;
 
        // If N is a multiple of 2
        else if (n % 2 == 0)
            return false;
 
        // Otherwise, check for the
        // odds values
        for (int i = 3;
             i <= Math.sqrt(n); i += 2) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
 
    // Function to check if S1 can be
    // a permutation of S2 by adding
    // or removing characters from S1
    private static void checkPermutation(
        String s1, String s2)
    {
        // Initialize a frequency array
        int freq[] = new int[26];
 
        // Decrement the frequency for
        // occurrence in s1
        for (char ch : s1.toCharArray()) {
            freq[ch - 'a']--;
        }
 
        // Increment the frequency for
        // occurence in s2
        for (char ch : s2.toCharArray()) {
            freq[ch - 'a']++;
        }
 
        boolean isAllChangesPrime = true;
 
        for (int i = 0; i < 26; i++) {
 
            // If frequency of current
            // char is same in s1 and s2
            if (freq[i] == 0) {
                continue;
            }
 
            // Check the frequency for
            // the current char is not
            // prime
            else if (!isPrime(
                         Math.abs(freq[i]))) {
                isAllChangesPrime = false;
                break;
            }
        }
 
        // Print the result
        if (isAllChangesPrime) {
            System.out.println("Yes");
        }
        else {
            System.out.println("No");
        }
    }
 
    // Driver Code
    public static void main(
        String[] args)
    {
 
        String S1 = "gekforgk";
        String S2 = "geeksforgeeks";
        checkPermutation(S1, S2);
    }
}


Python3
# Python 3 program for the above approach
 
from math import sqrt
# Function to check if the given
# number is prime or not
def isPrime(n):
    # If the number is less than 2
    if (n <= 1):
        return False
 
    # If the number is 2
    elif(n == 2):
        return True
 
    # If N is a multiple of 2
    elif(n % 2 == 0):
        return False
 
    # Otherwise, check for the
    # odds values
    for i in range(3,int(sqrt(n))+1,2):
        if (n % i == 0):
            return False
    return True
 
# Function to check if S1 can be
# a permutation of S2 by adding
# or removing characters from S1
def checkPermutation(s1, s2):
    # Initialize a frequency array
    freq = [0 for i in range(26)]
     
    # Decrement the frequency for
    # occurrence in s1
    for ch in s1:
        if ord(ch) - 97 in freq:
            freq[ord(ch) - 97] -= 1
        else:
            freq[ord(ch) - 97] = 1
 
    # Increment the frequency for
    # occurence in s2
    for ch in s2:
        if ord(ch) - 97 in freq:
            freq[ord(ch) - 97] += 1
        else:
            freq[ord(ch) - 97] = 1
 
    isAllChangesPrime = True
 
    for i in range(26):
        # If frequency of current
        # char is same in s1 and s2
        if (freq[i] == 0):
            continue
 
        # Check the frequency for
        # the current char is not
        # prime
        elif(isPrime(abs(freq[i]))==False):
            isAllChangesPrime = False
            break
 
    # Print the result
    if (isAllChangesPrime==False):
        print("Yes")
    else:
        print("No")
 
# Driver Code
if __name__ == '__main__':
    S1 = "gekforgk"
    S2 = "geeksforgeeks"
     
    checkPermutation(S1, S2)
     
    # This code is contributed by SURENDRA_GANGWAR.


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to check if the given
// number is prime or not
private static bool isPrime(int n)
{
     
    // If the number is less than 2
    if (n <= 1)
        return false;
 
    // If the number is 2
    else if (n == 2)
        return true;
 
    // If N is a multiple of 2
    else if (n % 2 == 0)
        return false;
 
    // Otherwise, check for the
    // odds values
    for(int i = 3; i <= Math.Sqrt(n); i += 2)
    {
        if (n % i == 0)
            return false;
    }
    return true;
}
 
// Function to check if S1 can be
// a permutation of S2 by adding
// or removing characters from S1
private static void checkPermutation(
    string s1, string s2)
{
     
    // Initialize a frequency array
    int[] freq = new int[26];
 
    // Decrement the frequency for
    // occurrence in s1
    foreach (char ch in s1.ToCharArray())
    {
        freq[ch - 'a']--;
    }
 
    // Increment the frequency for
    // occurence in s2
    foreach (char ch in s2.ToCharArray())
    {
        freq[ch - 'a']++;
    }
 
    bool isAllChangesPrime = true;
 
    for(int i = 0; i < 26; i++)
    {
         
        // If frequency of current
        // char is same in s1 and s2
        if (freq[i] == 0)
        {
            continue;
        }
 
        // Check the frequency for
        // the current char is not
        // prime
        else if (!isPrime(Math.Abs(freq[i])))
        {
            isAllChangesPrime = false;
            break;
        }
    }
 
    // Print the result
    if (isAllChangesPrime != false)
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    string S1 = "gekforgk";
    string S2 = "geeksforgeeks";
     
    checkPermutation(S1, S2);
}
}
 
// This code is contributed by target_2


Javascript


输出:
Yes

时间复杂度: O(max(N, M))
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程