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!
>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.