从简单的开始记录
Q:
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.
A:
class Solution {
public:int lengthOfLongestSubstring(string s) {
if (s.length()==0) return 0;
int last_pos[256];
int a;
memset(last_pos,-1,sizeof(last_pos));
int ans=1;
a=1;last_pos[(int)s[0]]=0;
for (int i=1;i<s.length();++i)
{
int b=(int)s[i];
a=(a+1<i-last_pos[b]?a+1:i-last_pos[b]);
last_pos[b]=i;
ans=(ans>a?ans:a);
}
return ans;
}
};