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

Time:12-03

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!

CodePudding user response:

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.

CodePudding user response:

word1.begin() is the iterator that points to the first character in the string word1. word1.end() is the iterator that points to the position after the last character in the string word1. Together, they define the range of elements in the string word1 that will be added to a std::setobject.

set(word1.begin(),word1.end()) creates a temporary std::set object that contains all the characters in the string word1.

std::set is a container that stores unique elements in a specific order. In this case, the std::set object will have all of the unique characters in the string word1 in a specific order.

That std::set object is then compared to another temporary std::set object being created from the string word2, to see if the two sets of characters are equal. If they are not equal, it means that the two strings do not have the same set of unique characters and the function will return false.

CodePudding user response:

Strings can be thought of as containers for char. Thus it's possible to define iterators for them (that visit them in-order, char-by-char). word1.begin() and word1.end() are simply the iterators to the first character and to the end of string.

  •  Tags:  
  • c
  • Related