a=abcabcbb,则a的无重复最长字串是abc,长度为3
解题思路:无重复最长子串一旦出现重复的字符,起点一定会变为上一个出现的重复字符的后一个字符。
第一种 为了方便判断是否有重复字符的出现,选用set作为去重的数据结构。
1.从第一个字符开始遍历,如果set中不存在重复的字符,则继续向后遍历,并把字符放入set中。
2.当出现重复字符的时候,(此时指针指向的值是重复的值得前一个,因为计算的是不重复的大小),一旦出现重复的值,就把前面的字符删除,直至set中不重复。
3.得出最大长度。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
//map<char,int> test;
set<char> test;
int i=0;
int j=0;
int count=0;
int max=0;
if(s=="")
{
return 0;
}
if(s.size()==1)
{
return 1;
}
test.insert(s[0]);
for(i=0;i<s.length();i++)
{
if(i!=0)
{
test.erase(s[i-1]);
count--;
}
while(j+1<s.length()&&test.count(s[j+1])==0)
{
test.insert(s[j+1]);
count++;
j++;
}
if(test.size()>max)
{
max=test.size();
}
}
return max;
}
};
第二种 选用map作为去重的数据结构
因为使用set,导致在去除重复字符的过程中,有多次删除的情况。
为避免上述的情况,使用map。
1.start指针与end指针同时指向第一个字符,然后end指针向后推进,每遇到一个字符就把字符及其位置+1放入到map中。
2.当检测到重复的情况后,start指针有两种变化方式,第一种是指向重复字符的pos,第二种是原地不动。
3.计算end-start+1与max谁大,并返回结果值。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char,int> test;
int start=0;
int max=0;
int end=0;
while(end<s.length())
{
if(test.count(s[end]))
{
if(start<test[s[end]])//test[s[end]]大的情况出现在之前的重复值在这个重复值位置的前面
{
start = test[s[end]];//指针指向前一个重复值的后边
}
}
if(max<end-start+1)
{
max = end-start+1;
}
test[s[end]]= end+1;
end++;
}
return max;
}
};