Hello everyone.
I was solving Custom Sort String and I tried the below code at first , but it didn't work, giving runtime error( error message-> AddressSanitizer: heap-buffer-overflow on address 0x60b000003d6f ). Inside bool operator(), I used <=.
class Comparator{
public:
vector<int> order;
Comparator(string s) {
order.resize(26);
int i = 1;
for(char c : s) {
order[c-'a'] = i++;
}
}
bool operator() (char& first, char& second) {
if(order[first-'a'] <= order[second-'a']) {
return true;
}
else {
return false;
}
}
};
class Solution {
public:
string customSortString(string order, string str) {
sort(str.begin(), str.end(), Comparator(order));
return str;
}
};But when I used only < instead of <=, it passed. Does anyone know why it didn't pass for <= ? (I tried print statements inside bool operator() to print the two characters, but one of the characters was not getting printed leading to the runtime error, but why is it happening)