Question:
Given a string, find the length of the longest substring without repeating characters.
Ex:
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.
Algorithm:Hash Table、Two Pointers
1、给出i,j分别表示不重复的开头和结尾,max_length记录最大长度,
2、j一直往右,同时用哈希表记录出现的字符,直到,有字符出现了两次,这时,i就应该到重复字符第一次出现的位置的下一位。
3、有字符出现两个次时,记录当前的子字符串长度cur_length,并和max_length作比较,如果比max_length大则更新。
Submitted Code:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.size()<2)return s.size();
int i=0; //begin
int j=0; //end
int cur_length=0;
int max_length=0;
map<char,int> hash;
while(j<s.size())
{
if(hash[s[j]]==0)
{
hash[s[j]]=1;
j++;
}
else
{
while(s[i]!=s[j]) //找到重复字符第一次出现的位置
{
hash[s[i]]=0;
i++;
}
i++;
j++;
}
cur_length = j-i;
max_length = max_length>cur_length?max_length:cur_length;
}
return max_length;
}
};
hash表中存字符和下标之间的对应关系,其他思想与上述类似
class DistinctSubstring {
public:
int longestSubstring(string A, int n) {
// write code here
int i=0,j=0,res=0,curLen=0;
map<char,int> hash;
for(char i:A)
hash[i]=-1;
while(j<n){
if(hash[A[j]]==-1){
hash[A[j]]=j;
j++;
}
else{
while(i<hash[A[j]]){
hash[A[i]]=-1;
i++;
}
hash[A[i]]=j;
i++;
j++;
}
curLen=j-i;
res=max(curLen,res);
}
return res;
}
};