难度中等4221收藏分享切换为英文关注反馈
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其
长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b"
,所以其长度为 1。
示例 3:
输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是"wke"
,所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke"
是一个子序列,不是子串。
通过次数628,693提交次数1,771,456
错了5次,第六次提交过了。
说一下思路吧,算了,思路还是比较简单的,关键点记录一个nstart,如果map[c]<nstart说明 此时的c已经不再跟本次的这个逻辑冲突了,按之前没出现过c处理,因为我们处理的是start~目前出现c这个位置之间的长度,start之前的不管,之后出现c的话就更新c的位置就行了。
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
struct Section
{
int x;
int y;
Section (int x, int y) : x(x), y(y) {}
};
static int cmp(Section a, Section b)
{
if (a.y-a.x != b.y-b.x)
return a.y - a.x > b.y - b.x;
return a.x > b.x;
}
int lengthOfLongestSubstring(string s) {
map<char, int> map_c;
int nlen = s.size();
if(nlen == 0)
return 0;
int ans = 0;
int nans = 1;
int nstart = 0;
for (int i = 0; i < nlen;i++)
{
char c = s[i];
if (map_c.find(c) != map_c.end() )
{
if (map_c[c] < nstart)//不用更新
{
ans++;
nans = max(ans, nans);
map_c[c] = i;
}
else
{
ans = (i - map_c[c]);
nstart = map_c[c] +1;
map_c[c] = i;
}
}
else
{
ans++;
nans = max(ans, nans);
map_c[c] = i;
}
}
return nans;
}
int main()
{
string str;
while (1)
{
cin >> str;
cout << lengthOfLongestSubstring(str) << endl;;
}
return 0;
}