美文网首页PythonHackerRank
HackerRank:Strings: Making Anagr

HackerRank:Strings: Making Anagr

作者: 流浪山人 | 来源:发表于2019-12-05 17:41 被阅读0次

    题目

    Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not.

    Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number?

    Given two strings, and , that may or may not be of the same length, determine the minimum number of character deletions required to make and anagrams. Any characters can be deleted from either of the strings.

    For example, if and , we can delete from string and from string so that both remaining strings are and which are anagrams.

    Function Description

    Complete the makeAnagram function in the editor below. It must return an integer representing the minimum total characters that must be deleted to make the strings anagrams.

    makeAnagram has the following parameter(s):

    a: a string
    b: a string
    Input Format

    The first line contains a single string, .
    The second line contains a single string, .

    Constraints

    The strings and consist of lowercase English alphabetic letters ascii[a-z].
    Output Format

    Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other.

    Sample Input

    cde
    abc
    Sample Output

    4
    Explanation

    We delete the following characters from our two strings to turn them into anagrams of each other:

    Remove d and e from cde to get c.
    Remove a and b from abc to get c.
    We must delete characters to make both strings anagrams, so we print on a new line.

    题目解析

    两个数组去重问题,可以借助字典,每个字母的count值出来,把两者中不同的个数统计出来就行了。

    ANSWER

    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    from collections import Counter
    
    # Complete the makeAnagram function below.
    def makeAnagram(a, b):
        a_c=Counter(a)
        b_c=Counter(b)
        deletecount=0
        for i in a_c.keys():
            deletecount +=abs(a_c[i]-b_c[i])
            del b_c[i]
        
        deletecount +=sum(b_c.values())  
        return  deletecount
    
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        a = input()
    
        b = input()
    
        res = makeAnagram(a, b)
    
        fptr.write(str(res) + '\n')
    
        fptr.close()
    
    

    相关文章

      网友评论

        本文标题:HackerRank:Strings: Making Anagr

        本文链接:https://www.haomeiwen.com/subject/ynhjgctx.html