Posted on

Description

Submission

class Solution {
public:
    bool closeStrings(string word1, string word2) {
        // case 1: sort
        // case 2: counter + sort
        if(word1.length() != word2.length()) return false;
        
        sort(word1.begin(), word1.end());
        sort(word2.begin(), word2.end());
        if(word1 == word2) return true;
        
        int counter1[26] = {0};
        int counter2[26] = {0};
        
        int n = word1.size();
        for(int i = 0; i < n; ++i) {
            counter1[word1[i]-'a']++;
            counter2[word2[i]-'a']++;
        }
        
        // same alphabet
        for(int i = 0; i < 26; ++i) {
            if(counter1[i] == 0 && counter2[i] != 0) return false;
            if(counter1[i] != 0 && counter2[i] == 0) return false;

        }
        
        sort(counter1, counter1 + 26);
        sort(counter2, counter2 + 26);
        
        for(int i = 0; i < 26; ++i) {
            if(counter1[i] != counter2[i]) return false;
        }
        
        return true;
    }
};

Submission 210311

class Solution {
public:
    bool closeStrings(string word1, string word2) {
        if(word1.length() != word2.length()) return false;
        map<char, int> m1;
        map<char, int> m2;
        
        for(char c: word1) {
            m1[c]++;
        }
        
        for(char c: word2) {
            m2[c]++;
        }
        
        vector<int> v1, v2;
        set<char> o1, o2;
        for(auto iter = m1.begin(); iter != m1.end(); iter++) {
            v1.push_back(iter->second);
            o1.insert(iter->first);
        }
        
        for(auto iter = m2.begin(); iter != m2.end(); iter++) {
            v2.push_back(iter->second);
            o2.insert(iter->first);
        }
        
        if(o2.size() != o1.size()) return false;
        
        sort(v1.begin(), v1.end());
        sort(v2.begin(), v2.end());
        
        for(auto iter1 = o1.begin(), iter2 = o2.begin(); iter1 != o1.end(); iter1++, iter2++) {
            if(*iter1 != *iter2) return false;
        }
        
        
        for(int i = 0; i < v1.size(); ++i) {
            if(v1[i] != v2[i]) return false;
        }
        
        return true;
    }
};

Leave a Reply

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