Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
和 boyer-moore算法的skip table有类似的地方,就是做一个基于 256 char set的 table, 不过是一个bool table. 首先是如何确定是重复,就是同一字符出现两次。 然后就是如何更新不同的substring. 一旦发现字符重复,计算长度,然后重设bool table,继续scan。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
/*use bool table to fast access record*/
bool tbl[256]={false};
int bgn=0,end=0,size=s.size();
int length=0;
while(end<size){
if (tbl[s[end]]){
length=max(length,end-bgn);
while(s[bgn]!=s[end])
tbl[s[bgn++]]=false;
bgn++;
end++;
} else {
tbl[s[end++]]=true;
}
}
return max(length,end-bgn);
}
};