LeetCode 0242. Valid Anagram Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0242. Valid Anagram

Description

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

 

Example 1:

Input: s = "anagram", t = "nagaram"

Output: true

Example 2:

Input: s = "rat", t = "car"

Output: false

 

Constraints:

  • 1 <= s.length, t.length <= 5 * 104
  • s and t consist of lowercase English letters.

 

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

Solutions

Solution 1: Counting

We first determine whether the length of the two strings is equal. If they are not equal, the characters in the two strings must be different, so return false.

Otherwise, we use a hash table or an array of length 26 to record the number of times each character appears in the string s, and then traverse the other string t. Each time we traverse a character, we subtract the number of times the corresponding character appears in the hash table by one. If the number of times after subtraction is less than 0, the number of times the character appears in the two strings is different, return false. If after traversing the two strings, all the character counts in the hash table are 0, it means that the characters in the two strings appear the same number of times, return true.

The time complexity is O(n), the space complexity is O(C), where n is the length of the string; and C is the size of the character set, which is C=26 in this problem.

PythonJavaC++GoTypeScriptRustJavaScriptC#C
class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False cnt = Counter(s) for c in t: cnt[c] -= 1 if cnt[c] < 0: return False return True(code-box)

Solution 2

PythonRustC
class Solution: def isAnagram(self, s: str, t: str) -> bool: return Counter(s) == Counter(t)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !