Time limit exceeded


  • 0
    S

    I realize that my code is inefficient, and that is why it results in "time limit exceeded" when an input like "hhbywxfzydbppjxnb..." is given. Can anyone give me suggestions to speed up my code? Thanks.

    class Solution {
    public:
        bool isAnagram(string s, string t) {
            if (s.length() != t.length()) {
                return false;
            }
            
            if (s.length() == 0 && t.length() == 0) {
                return true;
            }
            
            int j = 0;
            
            while (j < s.length()-1) {
                for (int i = 1; i < s.length(); i++) {
                    if (s[j] >= s[i]) {
                        char tmp = s[j];
                        s[j] = s[i]; 
                        s.erase(s.begin()+i);
                        s.insert(j+1, 1, tmp);
                    }
                    if (t[j] >= t[i]) {
                        char tmp2 = t[j];
                        t[j] = t[i]; 
                        t.erase(t.begin()+i);
                        t.insert(j+1, 1, tmp2);
                    }
                }
                j++;
            }
            
            for (int l = 0; l < s.length(); l++) {
                if (s[l] != t[l]) {
                    return false;
                    cout << s[l];
                }
            }
            
            return true;
        }
    };

Log in to reply
 

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