Given a string, find the length of the longest substring without repeating characters.
Solution in C++:
int lengthOfLongestSubstring(string s) {
int *char_index = (int*)malloc(sizeof(int) * 256);
int max_len = 1;
int cur_len = 1;
if(s.length() == 0){
return 0;
}
//Initializing all the index values with -1 which means the character never appaered before
for(int iter = 0; iter < 256; ++iter){
char_index[iter] = -1;
}
//Assigning first character index as 0
char_index[s[0]] = 0;
//Iterating over each character and keeping track of max lenght
for(int iter = 1; iter < s.length(); ++iter){
int prev_index = char_index[s[iter]];
//Either the character is encountered for the first time or the character was part of previous sub string
if((prev_index == -1) || (iter - cur_len > prev_index)){
++cur_len;
cout<<"current lenght is: "<<cur_len<<endl;
} else {
if(cur_len > max_len){
max_len = cur_len;
}
cur_len = iter - prev_index;
}
char_index[s[iter]] = iter;
}
if(cur_len > max_len){
max_len = cur_len;
}
free(char_index);
return max_len;
}
Solution in C++:
int lengthOfLongestSubstring(string s) {
int *char_index = (int*)malloc(sizeof(int) * 256);
int max_len = 1;
int cur_len = 1;
if(s.length() == 0){
return 0;
}
//Initializing all the index values with -1 which means the character never appaered before
for(int iter = 0; iter < 256; ++iter){
char_index[iter] = -1;
}
//Assigning first character index as 0
char_index[s[0]] = 0;
//Iterating over each character and keeping track of max lenght
for(int iter = 1; iter < s.length(); ++iter){
int prev_index = char_index[s[iter]];
//Either the character is encountered for the first time or the character was part of previous sub string
if((prev_index == -1) || (iter - cur_len > prev_index)){
++cur_len;
cout<<"current lenght is: "<<cur_len<<endl;
} else {
if(cur_len > max_len){
max_len = cur_len;
}
cur_len = iter - prev_index;
}
char_index[s[iter]] = iter;
}
if(cur_len > max_len){
max_len = cur_len;
}
free(char_index);
return max_len;
}
Comments
Post a Comment