タイトル説明
のは、2つの文字列が異所性文字の単語であるかどうかを決定する方法を書いてみましょう、あなたは二つの文字列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)ハッシュマップ、キーの文字が表示され、文字の出現回数に対応する値を初期化することができます。
2)次に現れるプラスワンマップ内の文字の数に対応し、文字列sを横切ります。
3)次いで、反復ストリングTを介して、マイナス1の出現マップにおける文字の数に対応します。
4)最後に、すべての値がその上にマップで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'))