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;
}
本文介绍了一种算法,用于找出给定字符串中最长的不包含重复字符的子串长度。通过使用字符映射和滑动窗口技术,该算法能够有效地解决此问题。

769

被折叠的 条评论
为什么被折叠?



