Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
Subscribe to see which companies asked this question
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char,int> alpha2num;
int maxLen = 0, stratIndex=0;
for (int i = 0; i < s.size(); ++i)
{
if(alpha2num.count(s[i])) {
int loc = alpha2num[s[i]];
if(loc+1 > stratIndex) {
stratIndex = loc+1;
}
}
alpha2num[s[i]] = i;
if(i-stratIndex+1 > maxLen) {
maxLen = i-stratIndex+1;
}
}
return maxLen;
}
};
#include <iostream>
#include <string>
#include <cstdio>
#include <map>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char,int> alpha2num;
int maxLen = 0, stratIndex=0;
for (int i = 0; i < s.size(); ++i)
{
if(alpha2num.count(s[i])) {
int loc = alpha2num[s[i]];
if(loc+1 > stratIndex) {
stratIndex = loc+1;
}
alpha2num[s[i]] = i;
if(i-stratIndex+1 > maxLen) {
maxLen = i-stratIndex+1;
}
} else {
alpha2num[s[i]]=i;
if(maxLen < i+1-stratIndex)
maxLen = i+1-stratIndex;
}
}
return maxLen;
}
};
int main() {
Solution *ss = new Solution();
string s;
cin >> s;
int ans = ss->lengthOfLongestSubstring(s);
cout << ans << endl;
}