Why this method is too slow?


  • 0
    C

    class Solution {
    public:
    bool isAnagram(string s, string t) {

        // This method is too slow, why?
        int count = 0;
        if (s.size() != t.size())
            return false;
        else
        {
            for (int i = 0; i < s.size(); i++)
            {
                for (int j = 0; j < t.size(); j++)
                {
                    if (s[i] == t[j])
                    {
                        t[j] = 0;
                        count++;
                    }
                    else
                        continue;
                }
            }
            if (count == t.size())
                return true;
        }
    }
    

    };


  • 1
    D

    You shouldn't write loop in loop, just count the occur time of each character and determine if equal.


  • 0
    Z

    Your need to check out Time Complexity. The complexity of your code is O(N^2). Your runtime explodes as the input size grows.


Log in to reply
 

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