Super simple python code


  • -4
    M
    class Solution:
        # @param {string} s
        # @param {string} t
        # @return {boolean}
        def isAnagram(self, s, t):
            tmpS = list(s)
            tmpT = list(t)
            tmpS.sort()
            tmpT.sort()
            return (tmpS == tmpT)
    

    the speed is just 104 ms. anyone has any idea to make it faster?


  • 0
    C

    I'm using dictionary with time 76ms. But I think there should be better way.

    class Solution:
        # @param {string} s
        # @param {string} t
        # @return {boolean}
        def isAnagram(self, s, t):
            s_dic, t_dic = {}, {}
            for c in s:
                if c not in s_dic:
                    s_dic[c] = 1
                else:
                    s_dic[c] += 1
            for c in t:
                if c not in t_dic:
                    t_dic[c] = 1
                else:
                    t_dic[c] += 1
            return s_dic == t_dic

  • 0
    L

    of cource there is a better way. You don't need to know the order of the letters, you just gotta know if all the letters appear the same times. Notice that the in this problem, data is in the range of 'A' to 'z', so a look-up table sized 'z' would be enough. here is my code

    bool isAnagram(char* s, char* t)
    {
    int data['z'] = { 0 };
    int i = 'a'-1;
    while (*s != '\0' || *t != '\0')
    {
    	if (*s != '\0')
    	{
    		data[*s - 1]++;
    		s++;
    	}
    	if (*t != '\0')
    	{
    		data[*t - 1]--;
    		t++;
    	}
    }
    while (i < 'z')
    {
    	if (data[i] != 0)
    	{
    		return false;
    	}
    	i++;
    }
    return true;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.