I have provided the entire code for context:
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHARS = 256;
// Function to find smallest window containing
// all distinct characters
string findSubString(string str)
{
int n = str.length();
// Count all distinct characters.
int dist_count = 0;
bool visited[MAX_CHARS] = { false };
for (int i = 0; i < n; i++) {
if (visited[str[i]] == false) {
visited[str[i]] = true;
dist_count++;
}
}
int start = 0, start_index = -1, min_len = INT_MAX;
int count = 0;
int curr_count[MAX_CHARS] = { 0 };
for (int j = 0; j < n; j++) {
// Count occurrence of characters of string
curr_count[str[j]]++;
// If any distinct character matched,
// then increment count
if (curr_count[str[j]] == 1)
count++;
// if all the characters are matched
if (count == dist_count) {
// the section where i got it wrong
while (curr_count[str[start]] > 1) {
if (curr_count[str[start]] > 1)
curr_count[str[start]]--;
start++;
}
// end section where i got it wrong
// Update window size
int len_window = j - start + 1;
if (min_len > len_window) {
min_len = len_window;
start_index = start;
}
}
}
// Return substring starting from start_index
// and length min_len
return str.substr(start_index, min_len);
}
// Driver code
int main()
{
string str = "aabcbcdbca";
cout << "Smallest window containing all distinct"
" characters is: "
<< findSubString(str);
return 0;
}
please correct me if i'm wrong. The while loop already checks for the condition where count(current_char)>1. If that's the case what is the need to check for IF?
//code snippet 1:
while (curr_count[str[start]] > 1) {
if (curr_count[str[start]] > 1)
curr_count[str[start]]--;
start++;
}
// code snippet 2:
while (curr_count[str[start]] > 1) {
curr_count[str[start]]--;
start++;
}
input: aabcbcdbca
output(considering snippet 1) : 4
output(considering snippet 2) : 6 // the start pointer wasn't incrementing