Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update the algorithm for validate anagram #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions valid_anagram/solution2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""
Given two strings s and t, write a function to determine if t is an anagram of
s.

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Note:
You may assume the string contains only lowercase alphabets.
"""


class Solution(object):

def find_first(self, str, chr):
for i, ch in enumerate(str):
if ch == chr:
return i
return -1

def is_anagram(self, s, t):
if len(s) != len(t):
return False
s_idx = self.find_first(s, t[0])
s_idx_start = s_idx
if s_idx >= 0:
t_idx = 0
while True:
s_idx = (s_idx + 1) % len(s)
t_idx = (t_idx + 1) % len(s)
if s[s_idx] == t[t_idx] and s_idx != s_idx_start:
continue
elif s[s_idx] == t[t_idx] and s_idx == s_idx_start:
return True
elif s[s_idx] != t[t_idx]:
return False
else:
return False

s = Solution()
print(s.is_anagram("aacc", "ccac"))
print(s.is_anagram("abcd", "bcda"))
print(s.is_anagram("aabb", "abab"))