Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 91dd1e4

Browse files
committed
Create valid_anagram.py
1 parent 34f63d0 commit 91dd1e4

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

‎arrays_hashing/valid_anagram.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Given two strings s and t, return true if the two strings are anagrams of each other, otherwise return false.
2+
# An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
3+
# Example :
4+
# Input: s = "racecar", t = "carrace"
5+
# Output: true
6+
7+
# Method 1: Using Hashmap
8+
class Solution:
9+
def isAnagram(self, s: str, t: str) -> bool:
10+
11+
hashmap_s,hashmap_t = {},{}
12+
len_s,len_t = len(s),len(t)
13+
14+
if len_s != len_t:
15+
return False
16+
17+
for i in s:
18+
if i not in hashmap_s:
19+
hashmap_s[i] = 1
20+
else:
21+
hashmap_s[i] += 1
22+
23+
for j in t:
24+
if j not in hashmap_t:
25+
hashmap_t[j] = 1
26+
else:
27+
hashmap_t[j] += 1
28+
29+
return hashmap_s == hashmap_t
30+
31+
print(Solution.isAnagram(Solution,"racecar","carrace"))
32+
print(Solution.isAnagram(Solution,"jar","jam"))
33+
34+
35+
# Method 2: Using Sorting
36+
class Solution:
37+
def isAnagram(self, s: str, t: str) -> bool:
38+
39+
return sorted(s) == sorted(t)
40+
41+
print(Solution.isAnagram(Solution,"racecar","carrace"))
42+
print(Solution.isAnagram(Solution,"jar","jam"))
43+
44+
45+
# Method 3: Using Counter
46+
from collections import Counter
47+
class Solution:
48+
def isAnagram(self, s: str, t: str) -> bool:
49+
50+
return Counter(s) == Counter(t)
51+
52+
print(Solution.isAnagram(Solution,"racecar","carrace"))
53+
print(Solution.isAnagram(Solution,"jar","jam"))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /