Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: falseConstraints:
1 <= s.length, t.length <= 5 * 104sandtconsist of lowercase English letters.
SOLUTION:class Solution:def isAnagram(self, s: str, t: str) -> bool:if sorted(s)==sorted(t):return Trueelse:return False
The time complexity of the sorted() function is O(n log n), where n is the length of the input string. Therefore, sorting each string has a time complexity of O(n log n).
- Time complexity:
The code uses the
sorted()function twice, once for each input stringsandt. Thesorted()function returns a sorted list of characters from the input string. By comparing the sorted lists for both strings, the code checks if they are equal.If the sorted lists of both strings are equal, it means that the characters in the two strings are the same but in a different order. In this case, the code returns
True, indicating that the strings are anagrams of each other.If the sorted lists are not equal, it means that the characters in the two strings are different, and they cannot be anagrams. In this case, the code returns
False.
Comments
Post a Comment