leetcode-242 判断两个字符串是不是 Anagram ?
Posted Ethan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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'))
以上是关于leetcode-242 判断两个字符串是不是 Anagram ?的主要内容,如果未能解决你的问题,请参考以下文章