I was trying to solve LeetCode Problem 30 in C++ and was getting an error which should not have been possible in the given code below.
The problem arises when it is while (r <= s.size()-w)
and works fine if it is while (r+w <= s.size())
. Its technically the same thing then how is 1st part invalid and 2nd part valid??
class Solution {
vector<int> indices;
unordered_map<string, int> fm;
public:
vector<int> findSubstring(string s, vector<string>& words) {
for (const string &word: words)
fm[word]++;
const int w= words[0].size();
const int len= w*words.size();
for (int l, r, i= 0; i < w; i++) {
unordered_map<string, int> curr;
l= i, r= i;
while (r+w <= s.size()) { //Error if it is: while (r <= s.size()-w) {
string word= s.substr(r, w);
cout << r << '.' << word << ' ';
r+= w;
if (fm.find(word) == fm.end()) {
curr.clear();
l= r;
continue;
}
curr[word]++;
while (curr[word] > fm[word]) {
curr[s.substr(l, w)]--;
l+= w;
}
if (r-l == len)
indices.push_back(l);
}
}
return indices;
}
};
The specific error i was getting while running the testcase: s= "mississippi", words= ["mississippis"]
and the error was: terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr: __pos (which is 12) > this->size() (which is 11)
which is not possible as the loop will never execute!
Can anyone please explain??
I was trying to simply solve the problem but was confused on how while loop could execute even when the condition is FALSE!