zoukankan      html  css  js  c++  java
  • leetcode-242 判断两个字符串是不是 Anagram ?

    题目描述

    假设给定两个字符串 s 和 t, 让我们写出一个方法来判断这两个字符串是否是字母异位词?

    字母异位词就是,两个字符串中含有字母的个数和数量都一样,比如:

    Example 1:
    Input: s = "anagram", t = "nagaram"
    Output: true
    
    字符串 s 和 t 含有的字母以及字母的数量都一致,所以是 True.
    
    Example 2:
    Input: s = "rat", t = "car"
    Output: false
    
    字符串 s 中字母 "t" 在字符串 t 中并未出现,所以是 False. 
    

    解题思路

    1) 可以初始化一个 hash map,键作为出现的字母,值作为对应字母出现的次数。

    2)然后遍历字符串 s,将 map 中对应出现的字母个数加一。

    3)然后接着遍历字符串 t, 将 map 中对应出现的字母个数减一。

    4)最后判断 map 中是否所有的值都为 0 就可以了,如果不为 0 的话,一定表示 s 和 t 中拥有不同的字母。

    # Question:
    # Given two strings s and t , write a function to determine if t is an
    # anagram of s.
    
    # Type: string or array
    
    # Example 1:
    # Input: s = "anagram", t = "nagaram"
    # Output: true
    
    # Example 2:
    # Input: s = "rat", t = "car"
    # Output: false
    
    # Note:
    # You may assume the string contains only lowercase alphabets.
    
    # Follow up:
    # What if the inputs contain unicode characters?
    # How would you adapt your solution to such case?
    import string
    
    
    class Solution:
        def isAnagram(self, s: str, t: str) -> bool:
            # get all lower alphabets
            lower_alphabets = string.ascii_lowercase
    
            # we can init a hash map to represent the count of alphabets.
            lower_alphabets_map = {alphabet: 0 for alphabet in lower_alphabets}
    
            # Traverse the string "s" and plus 1 to the count of alphabet
            # that appear
            for index in s:
                if index in lower_alphabets_map.keys():
                    lower_alphabets_map[index] += 1
    
            # Then Traverse the string "t" and subtract 1 to the count of alphabet
            # that appear
            for index in t:
                if index in lower_alphabets_map.keys():
                    lower_alphabets_map[index] -= 1
    
            # if the count of all alphabets in the hash map is 0, then the string
            # "s" and "t" are anagrams.
            is_anagram = False
            for value in lower_alphabets_map.values():
                if value != 0:
                    return is_anagram
            return True
    
    
    if __name__ == '__main__':
        solution = Solution()
        print(solution.isAnagram('abc', 'abc'))
    
  • 相关阅读:
    event.preventDefault()
    laravel 授权使用gate门类
    Redis在Laravel项目中的应用实例详解
    Laravel实现找回密码及密码重置的例子
    2016-2017中国房地产走势大数据报告亮相
    特许金融分析师 (CFA) 持证人现在一般在做什么工作?职业分布是怎样的?
    工作中最常用的Excel函数公式大全
    151项国家职业资格目录清单公示
    中国 世界十大投资风云人物,谁是自己的指路明灯!
    世界十大投资风云人物,你知道几个?
  • 原文地址:https://www.cnblogs.com/michael9/p/11830809.html
Copyright © 2011-2022 走看看