题目
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, 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.
最长不重复子串问题,剑指offer原题。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> index(256,-1);//记录字符出现的位置
int maxRes=0,beg=0;
int n=s.size();
for(int i=0;i<n;++i){
if(index[s[i]]!=-1){//如果该字符之前出现过,考虑是否在当前截取的最长子串内,如果不在不用处理,如果在则更新最长子串长度,同时更新beg位置
if(index[s[i]]>=beg){
maxRes=max(maxRes,i-beg);
beg=index[s[i]]+1;
}
}
index[s[i]]=i;//更新字符索引处当前字符的出现位置
}
maxRes=max(maxRes,n-beg);//处理一下从beg到n是否是最长子串的情况,因为每次得到重复位置之后都更新beg,所以如果最后一个字符重复,则beg=n,不用担心,否则从beg到n的这个长度的子串没比较过,需要比较一次
return maxRes;
}
};