Leetcode 242: valid anagram

https://leetcode.com/problems/valid-anagram/

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.

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

 

 

Code

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if s is None and t is not None: return False
        if t is None and s is not None: return False
        if s is None and t is None: return True
        if len(s) != len(t): return False
        
        l = [0] * 26
        for c in s:
            l[ord(c) - ord('a')] += 1
        for c in t:
            l[ord(c) - ord('a')] -= 1
            
        for v in l:
            if v: return False
            
        return True

 

Idea

Create a dictionary counting occurrences of the 26 letters in `s` and `t`. You need O(N) time and O(N) space.

You can also use (in-place) sorting algorithms to solve this problem. You need O(NlogN) time and no space.

 

Reference

https://leetcode.com/discuss/50580/python-solutions-sort-and-dictionary

Leave a comment

Your email address will not be published. Required fields are marked *