Longest Substring Without Repeat

#include <iostream>
#include <string>
using namespace std;
class LongSubstring {
public:
       LongSubstring();
       ~LongSubstring();
       int getLongestSubstring(string s);
       string out;
       int maxlength;
private:
       bool isMax(int a, int b);
       void map_to_hash(char, int);
       int get_hash_value(char);
       void update(int, int);
       int start;
       int hash[26];
};
bool LongSubstring::isMax(int a, int b){
       if(a > b) return true;
       return false;
}
LongSubstring::LongSubstring() {
       for(int i = 0; i < 26; i++)
       {
              hash[i] = -1;
       }
       maxlength = 1;
       start = 0;
}
LongSubstring::~LongSubstring(){
}
int LongSubstring::getLongestSubstring(string s) {
       // Start typing your C/C++ solution below
       // DO NOT write int main() function
       if(s.size() == 0)
              return 0;
      
       int temp = 0;
       map_to_hash(s[0], 0);
       for(int i = 1; i < s.size(); i++){
              if(get_hash_value(s[i]) < temp){
                     map_to_hash(s[i], i);          
              }
              else{
                     temp = get_hash_value(s[i]) + 1;
                     map_to_hash(s[i], i);              
              }            
              if (!isMax(maxlength,  i-temp+1)) update(i, temp);
       }
       out.assign(s,start,maxlength);
       return maxlength;
}
void LongSubstring::update(int cur, int oldpos){
       start = oldpos;
       maxlength = cur-oldpos+1;
}
void LongSubstring::map_to_hash(char ch, int pos){
       hash[ch – ‘a’] = pos;
}
int LongSubstring::get_hash_value(char ch) {
       return hash[ch – ‘a’];
}
void main() {
       string str;
       //char* ch;
       LongSubstring ls;
       str = “abcabcdbb”;
       //ch = &str[0];
       cout<<ls.out<<”      length: “<<ls.getLongestSubstring(str)<<endl;

}

Leave a comment