码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-242 判断两个字符串是不是 Anagram ?

时间:2019-11-10 17:32:21      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:sum   hash   appear   初始   determine   unicode   ash   only   not   

题目描述

假设给定两个字符串 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'))

leetcode-242 判断两个字符串是不是 Anagram ?

标签:sum   hash   appear   初始   determine   unicode   ash   only   not   

原文地址:https://www.cnblogs.com/michael9/p/11830809.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!