Title Description
Given two strings s and t, t write a function to determine whether the ectopic letters of the word s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Description:
You can assume string contains only lowercase letters.
Topic solution
Method one: word frequency statistics to compare
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
from collections import Counter
maps = Counter(s)
mapt = Counter(t)
return maps == mapt
Method Two: Statistics letter No.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
c1 = [0]*26
c2 = [0]*26
for c in s:
pos = ord(c) - ord('a')
c1[pos] = c1[pos] + 1
for c in t:
pos = ord(c) - ord('a')
c2[pos] = c2[pos] + 1
return c1 == c2
Expand topics:
Source: https://www.v2ex.com/t/624125
questions asked: comparison of two words, the first look at whether a word after a word with the letters spliced out.
def can_be_composed(a, b):
a_count = collections.Counter(a)
b_count = collections.Counter(b)
return all(a_count[k] <= b_count.get(k, 0) for k in a_count)
The same train of thought, word frequency is not just an equal sign, with <=, using all ensure that all conditions are met.