add valid-anagram

This commit is contained in:
Sangeeth Sudheer 2022-04-21 13:32:57 +05:30
parent 4c4bf0bd5f
commit 1578bc52d6
4 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,22 @@
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: 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?

View File

@ -0,0 +1,13 @@
# Time: O(NlogN)
# Space: O(1)
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
slen, tlen = len(s), len(t)
if slen != tlen:
return False
return sorted(s) == sorted(t)

View File

@ -0,0 +1,8 @@
# Time: O(N)
# Space: O(N)
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)

View File

@ -0,0 +1,21 @@
# Time: O(N) where N is num of chars in string
# Space: O(N) where N is num of chars in string
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
slen, tlen = len(s), len(t)
if slen != tlen:
return False
scounts, tcounts = {}, {}
for i in range(slen):
sc, tc = s[i], t[i]
scounts[sc] = scounts.get(sc, 0) + 1
tcounts[tc] = tcounts.get(tc, 0) + 1
return scounts == tcounts