Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does set(str.begin(), str.end()) mean?

I was going through this question on leetcode: https://leetcode.com/problems/determine-if-two-strings-are-close/solutions/935916/c-o-nlogn-sort-hash-table-easy-to-understand/

class Solution {
public:
    bool closeStrings(string word1, string word2) {
        if(word1.size()!=word2.size())
            return false;
        int n = word1.size();
        vector<int>freq1(26,0);
        vector<int>freq2(26,0);
        for(int i= 0 ; i < n ; ++i){
            freq1[word1[i]-'a']++;
            freq2[word2[i]-'a']++;
        }
        sort(freq1.rbegin(),freq1.rend());
        sort(freq2.rbegin(),freq2.rend());
        **if(set(word1.begin(),word1.end())!=set(word2.begin(),word2.end()))**
            return false;
        for(int i= 0;i<26;++i){
            if(freq1[i]!=freq2[i])
                return false;
        }
        return true;
    }
};

I am not understanding what does set(word1.begin(),word1.end()) mean over here, I tried to search on the internet for answer but I didn’t got any satisfying answer, if someone can explain it would be very helpful. Thanks in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It creates a set of the characters in word1, which is just the unique characters and in a way that could be compared to another word without the number of occurrences or order mattering.

So, comparing sets made this way, "cat" and "taca" would have == sets. "cat" and "taco" would not. "cat" and "kat" would not, but "dog" and "good" would.

So, this code is saying that if the words do not share all of the same letters, then they would not be considered close.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading