📌  相关文章
📜  删除最少字符数,使两个字符串变为 anagram

📅  最后修改于: 2022-05-13 01:57:08.954000             🧑  作者: Mango

删除最少字符数,使两个字符串变为 anagram

给定两个小写字符串,任务是使它们变位。唯一允许的操作是从任何字符串中删除一个字符。找到要删除的最少字符数以使两个字符串都变位?
如果两个字符串以任何顺序包含相同的数据集,则字符串称为Anagrams

例子 :

Input : str1 = "bcadeh" str2 = "hea"
Output: 3
We need to remove b, c and d from str1.

Input : str1 = "cddgk" str2 = "gcd"
Output: 2

Input : str1 = "bca" str2 = "acb"
Output: 0

这个想法是为每个字符的字符串和存储频率创建字符计数数组。现在迭代两个字符串的计数数组,两个字符串中任何字符的频率差异abs(count1[str1[i]-'a'] – count2[str2[i]-'a'])是字符串字符要在任一字符串中删除。

C++
// C++ program to find minimum number of characters
// to be removed to make two strings anagram.
#include
using namespace std;
const int CHARS = 26;
 
// function to calculate minimum numbers of characters
// to be removed to make two strings anagram
int remAnagram(string str1, string str2)
{
    // make hash array for both string and calculate
    // frequency of each character
    int count1[CHARS] = {0}, count2[CHARS] = {0};
 
    // count frequency of each character in first string
    for (int i=0; str1[i]!='\0'; i++)
        count1[str1[i]-'a']++;
 
    // count frequency of each character in second string
    for (int i=0; str2[i]!='\0'; i++)
        count2[str2[i]-'a']++;
 
    // traverse count arrays to find number of characters
    // to be removed
    int result = 0;
    for (int i=0; i<26; i++)
        result += abs(count1[i] - count2[i]);
    return result;
}
 
// Driver program to run the case
int main()
{
    string str1 = "bcadeh", str2 = "hea";
    cout << remAnagram(str1, str2);
    return 0;
}


Java
// Java program to find minimum number of
// characters to be removed to make two
// strings anagram.
import java.util.*;
 
class GFG {
 
    // function to calculate minimum numbers
    // of characters to be removed to make
    // two strings anagram
    static int remAnagram(String str1, String str2)
    {
        // make hash array for both string
        // and calculate frequency of each
        // character
        int count1[] = new int[26];
        int count2[] = new int[26];
 
        // count frequency of each character
        // in first string
        for (int i = 0; i < str1.length() ; i++)
            count1[str1.charAt(i) -'a']++;
     
        // count frequency of each character
        // in second string
        for (int i = 0; i < str2.length() ; i++)
            count2[str2.charAt(i) -'a']++;
 
        // traverse count arrays to find
        // number of characters to be removed
        int result = 0;
        for (int i = 0; i < 26; i++)
            result += Math.abs(count1[i] -
                               count2[i]);
        return result;
    }
 
    // Driver program to run the case
    public static void main(String[] args)
    {
        String str1 = "bcadeh", str2 = "hea";
        System.out.println(remAnagram(str1, str2));
    }
}
// This code is contributed by Prerna Saini


Python3
# Python 3 program to find minimum
# number of characters
# to be removed to make two
# strings anagram.
 
CHARS = 26
 
# function to calculate minimum
# numbers of characters
# to be removed to make two
# strings anagram
def remAnagram(str1, str2):
 
    # make hash array for both string
    # and calculate
    # frequency of each character
    count1 = [0]*CHARS
    count2 = [0]*CHARS
 
    # count frequency of each character
    # in first string
    i = 0
    while i < len(str1):
        count1[ord(str1[i])-ord('a')] += 1
        i += 1
 
    # count frequency of each character
    # in second string
    i =0
    while i < len(str2):
        count2[ord(str2[i])-ord('a')] += 1
        i += 1
 
    # traverse count arrays to find
    # number of characters
    # to be removed
    result = 0
    for i in range(26):
        result += abs(count1[i] - count2[i])
    return result
 
# Driver program to run the case
if __name__ == "__main__":
    str1 = "bcadeh"
    str2 = "hea"
    print(remAnagram(str1, str2))
     
# This code is contributed by
# ChitraNayal


C#
// C# program to find minimum
// number of characters to be
// removed to make two strings
// anagram.
using System;
 
class GFG
{
 
    // function to calculate
    // minimum numbers of
    // characters to be removed
    // to make two strings anagram
    static int remAnagram(string str1,
                          string str2)
    {
        // make hash array for both
        // string and calculate frequency
        // of each character
        int []count1 = new int[26];
        int []count2 = new int[26];
 
        // count frequency of each
        // character in first string
        for (int i = 0; i < str1.Length ; i++)
            count1[str1[i] -'a']++;
     
        // count frequency of each 
        // character in second string
        for (int i = 0; i < str2.Length ; i++)
            count2[str2[i] -'a']++;
 
        // traverse count arrays to
        // find number of characters
        // to be removed
        int result = 0;
        for (int i = 0; i < 26; i++)
            result += Math.Abs(count1[i] -
                               count2[i]);
        return result;
    }
 
    // Driver Code
    public static void Main()
    {
        string str1 = "bcadeh",
               str2 = "hea";
        Console.Write(remAnagram(str1, str2));
    }
}
 
// This code is contributed
// by nitin mittal.


PHP


Javascript


C++
// C++ implementation to count number of deletions
// required from two strings to create an anagram
#include 
using namespace std;
const int CHARS = 26;
 
int countDeletions(string str1, string str2)
{
    int arr[CHARS] = {0};
    for (int i = 0; i < str1.length(); i++)
        arr[str1[i] - 'a']++;
     
    for (int i = 0; i < str2.length(); i++)
        arr[str2[i] - 'a']--;
     
    long long int ans = 0;
    for(int i = 0; i < CHARS; i++)
        ans +=abs(arr[i]);
    return ans;
}
 
int main() {
    string str1 = "bcadeh", str2 = "hea";
    cout << countDeletions(str1, str2);
    return 0;
}


Java
// Java implementation to count number of deletions
// required from two strings to create an anagram
 
class GFG {
 
    final static int CHARS = 26;
 
    static int countDeletions(String str1, String str2) {
        int arr[] = new int[CHARS];
        for (int i = 0; i < str1.length(); i++) {
            arr[str1.charAt(i) - 'a']++;
        }
 
        for (int i = 0; i < str2.length(); i++) {
            arr[str2.charAt(i) - 'a']--;
        }
 
        int ans = 0;
        for (int i = 0; i < CHARS; i++) {
            ans += Math.abs(arr[i]);
        }
        return ans;
    }
 
    static public void main(String[] args) {
        String str1 = "bcadeh", str2 = "hea";
        System.out.println(countDeletions(str1, str2));
    }
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to find minimum
# number of characters to be
# removed to make two strings
# anagram.
 
# function to calculate minimum
# numbers of characters to be
# removed to make two strings anagram
def makeAnagram(a, b):
    buffer = [0] * 26
    for char in a:
        buffer[ord(char) - ord('a')] += 1
    for char in b:
        buffer[ord(char) - ord('a')] -= 1
    return sum(map(abs, buffer))
 
# Driver Code
if __name__ == "__main__" :
 
    str1 = "bcadeh"
    str2 = "hea"
    print(makeAnagram(str1, str2))
     
# This code is contributed
# by Raghib Ahsan


C#
// C# implementation to count number of deletions
// required from two strings to create an anagram
using System;
public class GFG {
  
    readonly static int CHARS = 26;
  
    static int countDeletions(String str1, String str2) {
        int []arr = new int[CHARS];
        for (int i = 0; i < str1.Length; i++) {
            arr[str1[i]- 'a']++;
        }
  
        for (int i = 0; i < str2.Length; i++) {
            arr[str2[i] - 'a']--;
        }
  
        int ans = 0;
        for (int i = 0; i < CHARS; i++) {
            ans += Math.Abs(arr[i]);
        }
        return ans;
    }
  
    static public void Main() {
        String str1 = "bcadeh", str2 = "hea";
        Console.WriteLine(countDeletions(str1, str2));
    }
}
  //This code is contributed by PrinciRaj1992


PHP


Javascript


输出 :

3

时间复杂度: O(n)
辅助空格: O(ALPHABET-SIZE)

可以优化上述解决方案以使用单计数数组。

C++

// C++ implementation to count number of deletions
// required from two strings to create an anagram
#include 
using namespace std;
const int CHARS = 26;
 
int countDeletions(string str1, string str2)
{
    int arr[CHARS] = {0};
    for (int i = 0; i < str1.length(); i++)
        arr[str1[i] - 'a']++;
     
    for (int i = 0; i < str2.length(); i++)
        arr[str2[i] - 'a']--;
     
    long long int ans = 0;
    for(int i = 0; i < CHARS; i++)
        ans +=abs(arr[i]);
    return ans;
}
 
int main() {
    string str1 = "bcadeh", str2 = "hea";
    cout << countDeletions(str1, str2);
    return 0;
}

Java

// Java implementation to count number of deletions
// required from two strings to create an anagram
 
class GFG {
 
    final static int CHARS = 26;
 
    static int countDeletions(String str1, String str2) {
        int arr[] = new int[CHARS];
        for (int i = 0; i < str1.length(); i++) {
            arr[str1.charAt(i) - 'a']++;
        }
 
        for (int i = 0; i < str2.length(); i++) {
            arr[str2.charAt(i) - 'a']--;
        }
 
        int ans = 0;
        for (int i = 0; i < CHARS; i++) {
            ans += Math.abs(arr[i]);
        }
        return ans;
    }
 
    static public void main(String[] args) {
        String str1 = "bcadeh", str2 = "hea";
        System.out.println(countDeletions(str1, str2));
    }
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 program to find minimum
# number of characters to be
# removed to make two strings
# anagram.
 
# function to calculate minimum
# numbers of characters to be
# removed to make two strings anagram
def makeAnagram(a, b):
    buffer = [0] * 26
    for char in a:
        buffer[ord(char) - ord('a')] += 1
    for char in b:
        buffer[ord(char) - ord('a')] -= 1
    return sum(map(abs, buffer))
 
# Driver Code
if __name__ == "__main__" :
 
    str1 = "bcadeh"
    str2 = "hea"
    print(makeAnagram(str1, str2))
     
# This code is contributed
# by Raghib Ahsan

C#

// C# implementation to count number of deletions
// required from two strings to create an anagram
using System;
public class GFG {
  
    readonly static int CHARS = 26;
  
    static int countDeletions(String str1, String str2) {
        int []arr = new int[CHARS];
        for (int i = 0; i < str1.Length; i++) {
            arr[str1[i]- 'a']++;
        }
  
        for (int i = 0; i < str2.Length; i++) {
            arr[str2[i] - 'a']--;
        }
  
        int ans = 0;
        for (int i = 0; i < CHARS; i++) {
            ans += Math.Abs(arr[i]);
        }
        return ans;
    }
  
    static public void Main() {
        String str1 = "bcadeh", str2 = "hea";
        Console.WriteLine(countDeletions(str1, str2));
    }
}
  //This code is contributed by PrinciRaj1992

PHP


Javascript


输出 :

3