📜  检查两个字符串是否为 k-anagrams

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

给定两个小写字母字符串和一个值 k,任务是找出两个字符串是否是彼此的 K-anagrams。
如果满足以下两个条件,则两个字符串称为k-anagrams

  1. 两者的字符数相同。
  2. 两个字符串最多可以通过改变一个字符串的k 个字符来变成字谜。

例子 :

Input:  str1 = "anagram" , str2 = "grammar" , k = 3
Output:  Yes
Explanation: We can update maximum 3 values and 
it can be done in changing only 'r' to 'n' 
and 'm' to 'a' in str2.

Input:  str1 = "geeks", str2 = "eggkf", k = 1
Output:  No
Explanation: We can update or modify only 1 
value but there is a need of modifying 2 characters. 
i.e. g and f in str 2.

方法一:
下面是检查两个字符串是否是彼此的 k-anagrams 的解决方案。

  1. 将两个字符串的所有字符的出现存储在单独的计数数组中。
  2. 计算两个字符串中不同字符的数量(在这里,如果一个字符串有 4 个 a,第二个有 3 个 ‘a’,那么它也将被计算在内。
  3. 如果不同字符的计数小于或等于 k,则返回 true 否则返回 false。
C++
// C++ program to check if two strings are k anagram
// or not.
#include
using namespace std;
const int MAX_CHAR = 26;
 
// Function to check that string is k-anagram or not
bool arekAnagrams(string str1, string str2, int k)
{
    // If both strings are not of equal
    // length then return false
    int n = str1.length();
    if (str2.length() != n)
        return false;
 
    int count1[MAX_CHAR] = {0};
    int count2[MAX_CHAR] = {0};
 
    // Store the occurrence of all characters
    // in a hash_array
    for (int i = 0; i < n; i++)
        count1[str1[i]-'a']++;
    for (int i = 0; i < n; i++)
        count2[str2[i]-'a']++;
      
    int count = 0;
 
    // Count number of characters that are
    // different in both strings
    for (int i = 0; i < MAX_CHAR; i++)
        if (count1[i] > count2[i])
            count = count + abs(count1[i]-count2[i]);
 
    // Return true if count is less than or
    // equal to k
    return (count <= k);
}
 
// Driver code
int main()
{
    string str1 = "anagram";
    string str2 = "grammar";
    int k = 2;
    if (arekAnagrams(str1, str2, k))
        cout << "Yes";
    else
        cout<< "No";
    return 0;
}


Java
// Java program to check if two strings are k anagram
// or not.
public class GFG {
      
    static final int MAX_CHAR = 26;
 
    // Function to check that string is k-anagram or not
    static boolean arekAnagrams(String str1, String str2,
                                                 int k)
    {
        // If both strings are not of equal
        // length then return false
        int n = str1.length();
        if (str2.length() != n)
            return false;
 
        int[] count1 = new int[MAX_CHAR];
        int[] count2 = new int[MAX_CHAR];
        int count = 0;
        
        // Store the occurrence of all characters
        // in a hash_array
        for (int i = 0; i < n; i++)
            count1[str1.charAt(i) - 'a']++;
        for (int i = 0; i < n; i++)
            count2[str2.charAt(i) - 'a']++;
 
        // Count number of characters that are
        // different in both strings
        for (int i = 0; i < MAX_CHAR; i++)
            if (count1[i] > count2[i])
                count = count + Math.abs(count1[i] -
                                          count2[i]);
 
        // Return true if count is less than or
        // equal to k
        return (count <= k);
    }
 
    // Driver code
    public static void main(String args[])
    {
        String str1 = "anagram";
        String str2 = "grammar";
        int k = 2;
        if (arekAnagrams(str1, str2, k))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
// This code is contributed by Sumit Ghosh


Python3
# Python3 program to check if two
# strings are k anagram or not.
MAX_CHAR = 26
 
# Function to check that is
# k-anagram or not
def arekAnagrams(str1, str2, k) :
 
    # If both strings are not of equal
    # length then return false
    n = len(str1)
    if (len(str2)!= n) :
        return False
 
    count1 = [0] * MAX_CHAR
    count2 = [0] * MAX_CHAR
 
    # Store the occurrence of all
    # characters in a hash_array
    for i in range(n):
        count1[ord(str1[i]) -
               ord('a')] += 1
    for i in range(n):
        count2[ord(str2[i]) -
               ord('a')] += 1
         
    count = 0
 
    # Count number of characters that
    # are different in both strings
    for i in range(MAX_CHAR):
        if (count1[i] > count2[i]) :
            count = count + abs(count1[i] -
                                count2[i])
 
    # Return true if count is less
    # than or equal to k
    return (count <= k)
 
# Driver Code
if __name__ == '__main__':
    str1 = "anagram"
    str2 = "grammar"
    k = 2
    if (arekAnagrams(str1, str2, k)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed
# by SHUBHAMSINGH10


C#
// C# program to check if two
// strings are k anagram or not.
using System;
class GFG {
     
    static int MAX_CHAR = 26;
 
    // Function to check that
    // string is k-anagram or not
    static bool arekAnagrams(string str1,
                             string str2,
                                      int k)
    {
         
        // If both strings are not of equal
        // length then return false
        int n = str1.Length;
        if (str2.Length != n)
            return false;
 
        int[] count1 = new int[MAX_CHAR];
        int[] count2 = new int[MAX_CHAR];
        int count = 0;
         
        // Store the occurrence
        // of all characters
        // in a hash_array
        for (int i = 0; i < n; i++)
            count1[str1[i] - 'a']++;
        for (int i = 0; i < n; i++)
            count2[str2[i] - 'a']++;
 
        // Count number of characters that are
        // different in both strings
        for (int i = 0; i < MAX_CHAR; i++)
            if (count1[i] > count2[i])
                count = count + Math.Abs(count1[i] -
                                         count2[i]);
 
        // Return true if count is
        // less than or equal to k
        return (count <= k);
    }
 
    // Driver code
    public static void Main()
    {
        string str1 = "anagram";
        string str2 = "grammar";
        int k = 2;
        if (arekAnagrams(str1, str2, k))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
// This code is contributed by nitin mittal.


PHP
 $count2[$i])
            $count = $count + abs($count1[$i] -
                                  $count2[$i]);
 
    // Return true if count is
    // less than or equal to k
    return ($count <= $k);
}
 
// Driver Code
$str1 = "anagram";
$str2 = "grammar";
$k = 2;
if (arekAnagrams($str1, $str2, $k))
    echo "Yes";
else
    echo "No";
 
// This code is contributed by m_kit
?>


Javascript


C++
// Optimized C++ program to check if two strings
// are k anagram or not.
#include
using namespace std;
 
const int MAX_CHAR = 26;
 
// Function to check if str1 and str2 are k-anagram
// or not
bool areKAnagrams(string str1, string str2, int k)
{
    // If both strings are not of equal
    // length then return false
    int n = str1.length();
    if (str2.length() != n)
        return false;
 
    int hash_str1[MAX_CHAR] = {0};
 
    // Store the occurrence of all characters
    // in a hash_array
    for (int i = 0; i < n ; i++)
        hash_str1[str1[i]-'a']++;
 
    // Store the occurrence of all characters
    // in a hash_array
    int count = 0;
    for (int i = 0; i < n ; i++)
    {
        if (hash_str1[str2[i]-'a'] > 0)
            hash_str1[str2[i]-'a']--;
        else
            count++;
 
        if (count > k)
            return false;
    }
 
    // Return true if count is less than or
    // equal to k
    return true;
}
 
// Driver code
int main()
{
    string str1 = "fodr";
    string str2 = "gork";
    int k = 2;
    if (areKAnagrams(str1, str2, k) == true)
        cout << "Yes";
    else
        cout << "No";
    return 0;
}


Java
// Optimized Java program to check if two strings
// are k anagram or not.
public class GFG {
     
    static final int MAX_CHAR = 26;
      
    // Function to check if str1 and str2 are k-anagram
    // or not
    static boolean areKAnagrams(String str1, String str2,
                                                  int k)
    {
        // If both strings are not of equal
        // length then return false
        int n = str1.length();
        if (str2.length() != n)
            return false;
      
        int[] hash_str1 = new int[MAX_CHAR];
      
        // Store the occurrence of all characters
        // in a hash_array
        for (int i = 0; i < n ; i++)
            hash_str1[str1.charAt(i)-'a']++;
      
        // Store the occurrence of all characters
        // in a hash_array
        int count = 0;
        for (int i = 0; i < n ; i++)
        {
            if (hash_str1[str2.charAt(i)-'a'] > 0)
                hash_str1[str2.charAt(i)-'a']--;
            else
                count++;
      
            if (count > k)
                return false;
        }
      
        // Return true if count is less than or
        // equal to k
        return true;
    }
      
    // Driver code
    public static void main(String args[])
    {
        String str1 = "fodr";
        String str2 = "gork";
        int k = 2;
        if (areKAnagrams(str1, str2, k) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
// This code is contributed by Sumit Ghosh


Python3
# Optimized Python3 program
# to check if two strings
# are k anagram or not.
MAX_CHAR = 26;
 
# Function to check if str1
# and str2 are k-anagram or not
def areKAnagrams(str1, str2, k):
    # If both strings are
    # not of equal length
    # then return false
 
    n = len(str1);
    if (len(str2) != n):
        return False;
 
    hash_str1 = [0]*(MAX_CHAR);
 
    # Store the occurrence of
    # all characters in a hash_array
    for i in range(n):
        hash_str1[ord(str1[i]) - ord('a')]+=1;
 
    # Store the occurrence of all
    # characters in a hash_array
    count = 0;
    for i in range(n):
        if (hash_str1[ord(str2[i]) - ord('a')] > 0):
            hash_str1[ord(str2[i]) - ord('a')]-=1;
        else:
            count+=1;
 
        if (count > k):
            return False;
 
    # Return true if count is
    # less than or equal to k
    return True;
 
# Driver code
str1 = "fodr";
str2 = "gork";
k = 2;
if (areKAnagrams(str1, str2, k) == True):
    print("Yes");
else:
    print("No");
         
# This code is contributed by mits


C#
// Optimized C# program to check if two strings
// are k anagram or not.
using System;
 
 class GFG {
     
    static  int MAX_CHAR = 26;
     
    // Function to check if str1 and str2 are k-anagram
    // or not
    static bool areKAnagrams(String str1, String str2,
                                                int k)
    {
        // If both strings are not of equal
        // [i] then return false
        int n = str1.Length;
        if (str2.Length != n)
            return false;
     
        int[] hash_str1 = new int[MAX_CHAR];
     
        // Store the occurrence of all characters
        // in a hash_array
        for (int i = 0; i < n ; i++)
            hash_str1[str1[i]-'a']++;
     
        // Store the occurrence of all characters
        // in a hash_array
        int count = 0;
        for (int i = 0; i < n ; i++)
        {
            if (hash_str1[str2[i]-'a'] > 0)
                hash_str1[str2[i]-'a']--;
            else
                count++;
     
            if (count > k)
                return false;
        }
     
        // Return true if count is less than or
        // equal to k
        return true;
    }
     
    // Driver code
     static void Main()
    {
        String str1 = "fodr";
        String str2 = "gork";
        int k = 2;
 
        if (areKAnagrams(str1, str2, k) == true)
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
// This code is contributed by Anuj_67


PHP
 0)
            $hash_str1[$str2[$i] - 'a']--;
        else
            $count++;
 
        if ($count > $k)
            return false;
    }
 
    // Return true if count is
    // less than or equal to k
    return true;
}
 
// Driver code
$str1 = "fodr";
$str2 = "gork";
$k = 2;
if (areKAnagrams($str1, $str2, $k) == true)
    echo "Yes";
else
    echo "No";
         
// This code is contributed by ajit
?>


Javascript


C++
// CPP program for the above approach
#include 
using namespace std;
 
// Function to check k
// anagram of two strings
bool kAnagrams(string str1, string str2, int k)
{
    int flag = 0;
 
    // First Condition: If both the
    // strings have different length ,
    // then they cannot form anagram
    if (str1.length() != str2.length())
        return false;
    int n = str1.length();
    // Converting str1 to Character Array arr1
    char arr1[n];
 
    // Converting str2 to Character Array arr2
    char arr2[n];
 
    strcpy(arr1, str1.c_str());
    strcpy(arr2, str2.c_str());
    // Sort arr1 in increasing order
    sort(arr1, arr1 + n);
 
    // Sort arr2 in increasing order
    sort(arr2, arr2 + n);
 
    vector list;
   
    // Iterate till str1.length()
    for (int i = 0; i < str1.length(); i++) {
 
        // Condition if arr1[i] is
        // not equal to arr2[i]
        // then add it to list
        if (arr1[i] != arr2[i]) {
            list.push_back(arr2[i]);
        }
    }
 
    // Condition to check if
    // strings for K-anagram or not
    if (list.size() <= k)
        flag = 1;
 
    if (flag == 1)
        return true;
    else
        return false;
}
 
// Driver Code
int main()
{
 
    string str1 = "anagram", str2 = "grammar";
    int k = 3;
 
    // Function Call
    kAnagrams(str1, str2, k);
    if (kAnagrams(str1, str2, k) == true)
        cout << "Yes";
    else
        cout << "No";
 
    // This code is contributed by bolliranadheer
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
     
// Function to check k
// anagram of two strings
public static boolean kAnagrams(String str1,
                                String str2, int k)
{
    int flag = 0;
     
    List list = new ArrayList<>();
     
    // First Condition: If both the
    // strings have different length ,
    // then they cannot form anagram
    if (str1.length() != str2.length())
        System.exit(0);
     
    // Converting str1 to Character Array arr1
    char arr1[] = str1.toCharArray();
     
    // Converting str2 to Character Array arr2
    char arr2[] = str2.toCharArray();
     
    // Sort arr1 in increasing order
    Arrays.sort(arr1);
     
    // Sort arr2 in increasing order
    Arrays.sort(arr2);
     
    // Iterate till str1.length()
    for (int i = 0; i < str1.length(); i++)
    {
         
        // Condition if arr1[i] is
        // not equal to arr2[i]
        // then add it to list
        if (arr1[i] != arr2[i])
        {
            list.add(arr2[i]);
        }
    }
     
    // Condition to check if
    // strings for K-anagram or not
    if (list.size() <= k)
        flag = 1;
 
    if (flag == 1)
        return true;
    else
        return false;
}
 
// Driver Code
public static void main(String[] args)
{
 
    String str1 = "fodr";
    String str2 = "gork";
    int k = 2;
     
    // Function Call
    kAnagrams(str1, str2, k);
    if (kAnagrams(str1, str2, k) == true)
        System.out.println("Yes");
    else
        System.out.println("No");
}
}


Python3
# Python 3 program for the above approach
import sys
 
# Function to check k
# anagram of two strings
 
 
def kAnagrams(str1, str2, k):
 
    flag = 0
 
    list1 = []
 
    # First Condition: If both the
    # strings have different length ,
    # then they cannot form anagram
    if (len(str1) != len(str2)):
        sys.exit()
 
    # Converting str1 to Character Array arr1
    arr1 = list(str1)
 
    # Converting str2 to Character Array arr2
    arr2 = list(str2)
 
    # Sort arr1 in increasing order
    arr1.sort()
 
    # Sort arr2 in increasing order
    arr2.sort()
 
    # Iterate till str1.length()
    for i in range(len(str1)):
 
        # Condition if arr1[i] is
        # not equal to arr2[i]
        # then add it to list
        if (arr1[i] != arr2[i]):
            list1.append(arr2[i])
 
    # Condition to check if
    # strings for K-anagram or not
    if (len(list1) <= k):
        flag = 1
 
    if (flag == 1):
        return True
    else:
        return False
 
 
# Driver Code
if __name__ == "__main__":
 
    str1 = "fodr"
    str2 = "gork"
    k = 2
 
    # Function Call
    kAnagrams(str1, str2, k)
    if (kAnagrams(str1, str2, k) == True):
        print("Yes")
    else:
        print("No")


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG
{
 
  // Function to check k
  // anagram of two strings
  public static bool kAnagrams(string str1, string str2, int k)
  {
    int flag = 0;
 
    List list = new List();
 
    // First Condition: If both the
    // strings have different length ,
    // then they cannot form anagram
    if (str1.Length != str2.Length)
    {
      return false;
    }
 
    // Converting str1 to Character Array arr1
    char[] arr1 = str1.ToCharArray();
 
    // Converting str2 to Character Array arr2
    char[] arr2 = str2.ToCharArray();
 
    // Sort arr1 in increasing order
    Array.Sort(arr1);
 
    // Sort arr2 in increasing order
    Array.Sort(arr2);
 
    // Iterate till str1.length()
    for (int i = 0; i < str1.Length; i++)
    {
 
      // Condition if arr1[i] is
      // not equal to arr2[i]
      // then add it to list
      if (arr1[i] != arr2[i])
      {
        list.Add(arr2[i]);
      }
    }
 
    // Condition to check if
    // strings for K-anagram or not
    if (list.Count <= k)
      flag = 1;
 
    if (flag == 1)
      return true;
    else
      return false;
  }
 
  // Driver Code
  static public void Main ()
  {
    string str1 = "fodr";
    string str2 = "gork";
    int k = 2;
 
    // Function Call
    kAnagrams(str1, str2, k);
    if (kAnagrams(str1, str2, k) == true)
      Console.WriteLine("Yes");
    else
      Console.WriteLine("No");
  }
}
 
// This code is contributed by avanitrachhadiya2155


Javascript


输出 :

Yes

方法二:
我们可以优化上述解决方案。这里我们只使用一个计数数组来存储 str1 中的字符计数。我们遍历 str2 并减少 str2 中存在的 count 数组中每个字符的出现次数。如果我们发现一个字符不存在str1中,我们增量次数不同的字符。如果不同字符的计数大于 k,则返回 false。

C++

// Optimized C++ program to check if two strings
// are k anagram or not.
#include
using namespace std;
 
const int MAX_CHAR = 26;
 
// Function to check if str1 and str2 are k-anagram
// or not
bool areKAnagrams(string str1, string str2, int k)
{
    // If both strings are not of equal
    // length then return false
    int n = str1.length();
    if (str2.length() != n)
        return false;
 
    int hash_str1[MAX_CHAR] = {0};
 
    // Store the occurrence of all characters
    // in a hash_array
    for (int i = 0; i < n ; i++)
        hash_str1[str1[i]-'a']++;
 
    // Store the occurrence of all characters
    // in a hash_array
    int count = 0;
    for (int i = 0; i < n ; i++)
    {
        if (hash_str1[str2[i]-'a'] > 0)
            hash_str1[str2[i]-'a']--;
        else
            count++;
 
        if (count > k)
            return false;
    }
 
    // Return true if count is less than or
    // equal to k
    return true;
}
 
// Driver code
int main()
{
    string str1 = "fodr";
    string str2 = "gork";
    int k = 2;
    if (areKAnagrams(str1, str2, k) == true)
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Java

// Optimized Java program to check if two strings
// are k anagram or not.
public class GFG {
     
    static final int MAX_CHAR = 26;
      
    // Function to check if str1 and str2 are k-anagram
    // or not
    static boolean areKAnagrams(String str1, String str2,
                                                  int k)
    {
        // If both strings are not of equal
        // length then return false
        int n = str1.length();
        if (str2.length() != n)
            return false;
      
        int[] hash_str1 = new int[MAX_CHAR];
      
        // Store the occurrence of all characters
        // in a hash_array
        for (int i = 0; i < n ; i++)
            hash_str1[str1.charAt(i)-'a']++;
      
        // Store the occurrence of all characters
        // in a hash_array
        int count = 0;
        for (int i = 0; i < n ; i++)
        {
            if (hash_str1[str2.charAt(i)-'a'] > 0)
                hash_str1[str2.charAt(i)-'a']--;
            else
                count++;
      
            if (count > k)
                return false;
        }
      
        // Return true if count is less than or
        // equal to k
        return true;
    }
      
    // Driver code
    public static void main(String args[])
    {
        String str1 = "fodr";
        String str2 = "gork";
        int k = 2;
        if (areKAnagrams(str1, str2, k) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
// This code is contributed by Sumit Ghosh

蟒蛇3

# Optimized Python3 program
# to check if two strings
# are k anagram or not.
MAX_CHAR = 26;
 
# Function to check if str1
# and str2 are k-anagram or not
def areKAnagrams(str1, str2, k):
    # If both strings are
    # not of equal length
    # then return false
 
    n = len(str1);
    if (len(str2) != n):
        return False;
 
    hash_str1 = [0]*(MAX_CHAR);
 
    # Store the occurrence of
    # all characters in a hash_array
    for i in range(n):
        hash_str1[ord(str1[i]) - ord('a')]+=1;
 
    # Store the occurrence of all
    # characters in a hash_array
    count = 0;
    for i in range(n):
        if (hash_str1[ord(str2[i]) - ord('a')] > 0):
            hash_str1[ord(str2[i]) - ord('a')]-=1;
        else:
            count+=1;
 
        if (count > k):
            return False;
 
    # Return true if count is
    # less than or equal to k
    return True;
 
# Driver code
str1 = "fodr";
str2 = "gork";
k = 2;
if (areKAnagrams(str1, str2, k) == True):
    print("Yes");
else:
    print("No");
         
# This code is contributed by mits

C#

// Optimized C# program to check if two strings
// are k anagram or not.
using System;
 
 class GFG {
     
    static  int MAX_CHAR = 26;
     
    // Function to check if str1 and str2 are k-anagram
    // or not
    static bool areKAnagrams(String str1, String str2,
                                                int k)
    {
        // If both strings are not of equal
        // [i] then return false
        int n = str1.Length;
        if (str2.Length != n)
            return false;
     
        int[] hash_str1 = new int[MAX_CHAR];
     
        // Store the occurrence of all characters
        // in a hash_array
        for (int i = 0; i < n ; i++)
            hash_str1[str1[i]-'a']++;
     
        // Store the occurrence of all characters
        // in a hash_array
        int count = 0;
        for (int i = 0; i < n ; i++)
        {
            if (hash_str1[str2[i]-'a'] > 0)
                hash_str1[str2[i]-'a']--;
            else
                count++;
     
            if (count > k)
                return false;
        }
     
        // Return true if count is less than or
        // equal to k
        return true;
    }
     
    // Driver code
     static void Main()
    {
        String str1 = "fodr";
        String str2 = "gork";
        int k = 2;
 
        if (areKAnagrams(str1, str2, k) == true)
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
// This code is contributed by Anuj_67

PHP

 0)
            $hash_str1[$str2[$i] - 'a']--;
        else
            $count++;
 
        if ($count > $k)
            return false;
    }
 
    // Return true if count is
    // less than or equal to k
    return true;
}
 
// Driver code
$str1 = "fodr";
$str2 = "gork";
$k = 2;
if (areKAnagrams($str1, $str2, $k) == true)
    echo "Yes";
else
    echo "No";
         
// This code is contributed by ajit
?>

Javascript


输出:

Yes

方法三:

  • 在这种方法中,想法是初始化一个数组或一个列表,基本情况是检查字符串,如果它们的长度不同,则它们不能形成字谜。
  • 否则将字符串转换为字符数组并对其进行排序。
  • 然后迭代直到字符串的长度,如果字符不相等,则将其添加到列表中,并检查列表大小是否小于等于 K,否则可以形成 K 字谜。

下面是上述方法的实现:

C++

// CPP program for the above approach
#include 
using namespace std;
 
// Function to check k
// anagram of two strings
bool kAnagrams(string str1, string str2, int k)
{
    int flag = 0;
 
    // First Condition: If both the
    // strings have different length ,
    // then they cannot form anagram
    if (str1.length() != str2.length())
        return false;
    int n = str1.length();
    // Converting str1 to Character Array arr1
    char arr1[n];
 
    // Converting str2 to Character Array arr2
    char arr2[n];
 
    strcpy(arr1, str1.c_str());
    strcpy(arr2, str2.c_str());
    // Sort arr1 in increasing order
    sort(arr1, arr1 + n);
 
    // Sort arr2 in increasing order
    sort(arr2, arr2 + n);
 
    vector list;
   
    // Iterate till str1.length()
    for (int i = 0; i < str1.length(); i++) {
 
        // Condition if arr1[i] is
        // not equal to arr2[i]
        // then add it to list
        if (arr1[i] != arr2[i]) {
            list.push_back(arr2[i]);
        }
    }
 
    // Condition to check if
    // strings for K-anagram or not
    if (list.size() <= k)
        flag = 1;
 
    if (flag == 1)
        return true;
    else
        return false;
}
 
// Driver Code
int main()
{
 
    string str1 = "anagram", str2 = "grammar";
    int k = 3;
 
    // Function Call
    kAnagrams(str1, str2, k);
    if (kAnagrams(str1, str2, k) == true)
        cout << "Yes";
    else
        cout << "No";
 
    // This code is contributed by bolliranadheer
}

Java

// Java program for the above approach
import java.util.*;
class GFG{
     
// Function to check k
// anagram of two strings
public static boolean kAnagrams(String str1,
                                String str2, int k)
{
    int flag = 0;
     
    List list = new ArrayList<>();
     
    // First Condition: If both the
    // strings have different length ,
    // then they cannot form anagram
    if (str1.length() != str2.length())
        System.exit(0);
     
    // Converting str1 to Character Array arr1
    char arr1[] = str1.toCharArray();
     
    // Converting str2 to Character Array arr2
    char arr2[] = str2.toCharArray();
     
    // Sort arr1 in increasing order
    Arrays.sort(arr1);
     
    // Sort arr2 in increasing order
    Arrays.sort(arr2);
     
    // Iterate till str1.length()
    for (int i = 0; i < str1.length(); i++)
    {
         
        // Condition if arr1[i] is
        // not equal to arr2[i]
        // then add it to list
        if (arr1[i] != arr2[i])
        {
            list.add(arr2[i]);
        }
    }
     
    // Condition to check if
    // strings for K-anagram or not
    if (list.size() <= k)
        flag = 1;
 
    if (flag == 1)
        return true;
    else
        return false;
}
 
// Driver Code
public static void main(String[] args)
{
 
    String str1 = "fodr";
    String str2 = "gork";
    int k = 2;
     
    // Function Call
    kAnagrams(str1, str2, k);
    if (kAnagrams(str1, str2, k) == true)
        System.out.println("Yes");
    else
        System.out.println("No");
}
}

蟒蛇3

# Python 3 program for the above approach
import sys
 
# Function to check k
# anagram of two strings
 
 
def kAnagrams(str1, str2, k):
 
    flag = 0
 
    list1 = []
 
    # First Condition: If both the
    # strings have different length ,
    # then they cannot form anagram
    if (len(str1) != len(str2)):
        sys.exit()
 
    # Converting str1 to Character Array arr1
    arr1 = list(str1)
 
    # Converting str2 to Character Array arr2
    arr2 = list(str2)
 
    # Sort arr1 in increasing order
    arr1.sort()
 
    # Sort arr2 in increasing order
    arr2.sort()
 
    # Iterate till str1.length()
    for i in range(len(str1)):
 
        # Condition if arr1[i] is
        # not equal to arr2[i]
        # then add it to list
        if (arr1[i] != arr2[i]):
            list1.append(arr2[i])
 
    # Condition to check if
    # strings for K-anagram or not
    if (len(list1) <= k):
        flag = 1
 
    if (flag == 1):
        return True
    else:
        return False
 
 
# Driver Code
if __name__ == "__main__":
 
    str1 = "fodr"
    str2 = "gork"
    k = 2
 
    # Function Call
    kAnagrams(str1, str2, k)
    if (kAnagrams(str1, str2, k) == True):
        print("Yes")
    else:
        print("No")

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG
{
 
  // Function to check k
  // anagram of two strings
  public static bool kAnagrams(string str1, string str2, int k)
  {
    int flag = 0;
 
    List list = new List();
 
    // First Condition: If both the
    // strings have different length ,
    // then they cannot form anagram
    if (str1.Length != str2.Length)
    {
      return false;
    }
 
    // Converting str1 to Character Array arr1
    char[] arr1 = str1.ToCharArray();
 
    // Converting str2 to Character Array arr2
    char[] arr2 = str2.ToCharArray();
 
    // Sort arr1 in increasing order
    Array.Sort(arr1);
 
    // Sort arr2 in increasing order
    Array.Sort(arr2);
 
    // Iterate till str1.length()
    for (int i = 0; i < str1.Length; i++)
    {
 
      // Condition if arr1[i] is
      // not equal to arr2[i]
      // then add it to list
      if (arr1[i] != arr2[i])
      {
        list.Add(arr2[i]);
      }
    }
 
    // Condition to check if
    // strings for K-anagram or not
    if (list.Count <= k)
      flag = 1;
 
    if (flag == 1)
      return true;
    else
      return false;
  }
 
  // Driver Code
  static public void Main ()
  {
    string str1 = "fodr";
    string str2 = "gork";
    int k = 2;
 
    // Function Call
    kAnagrams(str1, str2, k);
    if (kAnagrams(str1, str2, k) == true)
      Console.WriteLine("Yes");
    else
      Console.WriteLine("No");
  }
}
 
// This code is contributed by avanitrachhadiya2155

Javascript


输出:

Yes

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