版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32360995/article/details/86144490
题目:
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc"
, with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b"
, with the length of 1.
Example 3:
Input: "pwwkew" Output: 3 Explanation: The answer is"wke"
, with the length of 3. Note that the answer must be a substring,"pwke"
is a subsequence and not a substring.
题意:
找出字符串中拥有最长不重复字符的子串!!!不是子序列!!!
思路:
1、自己想的比较麻烦,偏暴力,用STL标准库函数的map容器标记已出现过的字符,设立一个头指针start指向子串开始的下标位置(因map容器初始值为0,故设下标位置从1开始)。遍历整个字符串,当前字符未出现过时将其放入map容器中,之前出现过则更新最长子串长度值,并清空从头指针start到当前字符上一次出现位置的值另其为0。另start指针指向当前字符上一次出现的位置+1,且更新当前字符在map容器中的值
2、因时间44ms看了不舒服就去看网上大佬的代码~看了之后泪流满面,我为何如此蠢???设一个标记字符出现位置的数组,因字符串不仅仅包括小写字母,就把数组长度设为128(跟字符的ascii码值有关)。标记数组及头指针start初始值为-1,遍历整个字符串,如果当前字符出现过,就更新start的值为当前字符上一次出现的位置+1(这里没有+1是为了方便计算长度)。每遍历一个字符就更新一次最长子串的长度值,然后更新当前字符在标记数组中的值~~~大佬真滴强,我真的是太菜了QAQ
Code:
思路1:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int i,j,maxr=0,start=0,len=s.length();
if(len==1) return 1;
map<char,int>q;
q[s[0]]=1;
for(i=1;i<len;i++){
if(q[s[i]]!=0){
maxr=max(maxr,i-start);
int k=q[s[i]];
for(j=start;j<k;j++) q[s[j]]=0;
start=k;
q[s[i]]=i+1;
}
else q[s[i]]=i+1;
}
maxr=max(maxr,len-start);
return maxr;
}
};
思路2:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int i,maxr=0,start=-1,len=s.length();
if(len==1) return 1;
int los[128];
memset(los,-1,sizeof(los));
for(i=0;i<len;i++){
if(los[s[i]]>start) start=los[s[i]];
maxr=max(maxr,i-start);
los[s[i]]=i;
}
return maxr;
}
};