1675_DetermineifTwoStringsAreClose - a920604a/leetcode GitHub Wiki


title: 1657. Determine if Two Strings Are Close tags: - sorting - hash table categories: leetcode comments: false


solution

class Solution {
public:
    bool closeStrings(string word1, string word2) {
        vector<int> vec1(26,0), vec2(26,0);
        for(char c:word1) vec1[c-'a']++;
        for(char c:word2) vec2[c-'a']++;
        vector<int> v1,v2;
        for(int a:vec1){
            if(a>0) v1.push_back(a);
        }
        for(int a:vec2){
            if(a>0) v2.push_back(a);
        }
        for(int i=0;i<26;++i){
            bool t1 = vec1[i]>0;
            bool t2 = vec2[i]>0;
            if( (!t1 && t2) || (!t2 && t1)) return false;
        }
        sort(v1.begin(), v1.end());
        sort(v2.begin(), v2.end());
        if(v1.size()!=v2.size()) return false;
        for(int i=0;i<v1.size() ;++i){
            if(v1[i] != v2[i]) return false;
        }
        return true;
    }
};

analysis

  • time complexity O(nlogn)
  • space complexity O(1)
⚠️ **GitHub.com Fallback** ⚠️