sorting + symbol table


  • 0
    N

    1.sorting

    public:
        bool isAnagram(string s, string t) {
            string sorted_s = s; 
            string sorted_t = t; 
            std::sort(sorted_s.begin(), sorted_s.end());
            std::sort(sorted_t.begin(), sorted_t.end());
            return !sorted_s.compare(sorted_t);
        }
    };
    
    1. symbol table
    class Solution {
    public:
        bool isAnagram(string s, string t) {
            if (s.length() != t.length()) {
                return false;
            }
            
            int table[256];
            memset(table, 0, sizeof(table));
            
            for (int i = 0; i < s.length(); i++) {
                table[s[i]]++;
                table[t[i]]--;
            }
    
            for (int i = 0; i < 256; i++) {
                if (table[i] != 0) {
                    return false;
                }
            }
            
            return true;
        }
    };
    

Log in to reply
 

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