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.
思路:
1. substring是连续的,不同与subsequence,可以是分离的。
2. 需要用two-pointer+hashtable:两个指针来界定substring开头和结尾,例如:”pwwkpew”, 每次把这个区间的字母和对应的位置存在hashtable。当扩展substring的结尾时,先看这个字母是否出现在hashtable, 如果没出现就先加入hashtable再substring的right++;如果该字母出现在hashtable,但查询到的坐标是小于substring的left,则先更新hashtable中这个字母的坐标,再right++;如果该字母出现的坐标比substring的left大,则需要移动left到该字母在hashtable中出现的坐标的下一个,再right++, 防止在substring中出现重复的字母!
3. 这类题,一般都可能有o(n)的解法,而且用hashtable和two pointer都可以降复杂度o(n^2)到o(n)
//棒!一次写成,通过OJ!
class Solution {
public:
int lengthOfLongestSubstring(string s) {
//hashtable+two-pointer
int mx=0;
int left=0,right=0;
vector<int> ss(256,-1);
for(int right=0;right<s.size();right++){
if(ss[s[right]]>=left){
left=ss[s[right]]+1;
}
ss[s[right]]=right;
mx=max(mx,right-left+1);
}
return mx;
}
};