0

I was working on a problem to find the longest substring without repeating characters. While trying for the solution I wrote this code. I'm not asking for the solution, but just the reason why the code works the way it does.

#include<iostream>
#include<map>
using namespace std;
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char,int> mp;
        map<char,int>::iterator it;
        int i=0,k=0,max=0;
        while(i<s.length()){
            it = mp.find(s[i]);
            if(it==mp.end()){
                k++;
            }
            else{
                k=k-distance(mp.begin(),it);
                cout<<distance(mp.begin(),it)<<" "; //this distance
                mp.erase(mp.begin(),it);
            }
            if(k>max){
                  max=k;  

            }
            mp.insert({s[i],1});
            i++;    
            }
        return max;
    }
};
int main(){
    Solution obj;
    cout<<obj.lengthOfLongestSubstring("yvyf");
}

When I give the input as "yvyf" it prints the distance as 1, but when I give the input as "avaf" or "pvpf", it prints the distance as 0.

learner
  • 45
  • 1
  • 7
  • 1
    Take a look at how elements of `std::map` are ordered. [This](https://stackoverflow.com/questions/7648756/is-the-order-of-iterating-through-stdmap-known-and-guaranteed-by-the-standard) post might also be helpful. – ChrisD Jun 13 '20 at 09:58
  • 1
    The best way to understand what a code does is to start the program in a debugger and step through the code line by line. Debugging is one of the first things a beginner should learn. – Thomas Sablik Jun 13 '20 at 10:03
  • Please in code questions give a [mre]--cut & paste & runnable code, including smallest representative example input as code; desired & actual output (including verbatim error messages); tags & versions; clear specification & explanation. Give the least code you can that is code that you show is OK extended by code that you show is not OK. (Debugging fundamental.) Find the first point in the execution where the state of the variables is not what it is supposed to be & say what you expected & why--justifying per language/library documentation. (Debugging fundamental.) Don't just dump wrong code. – philipxy Jul 04 '20 at 03:12

0 Answers0