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.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.empty())
return 0;
int hash[256];
memset(hash, -1,sizeof(hash));
int maxlength = 0;
int start = 0;
for (int i = 0; i < s.size();i++)
{
if (hash[s[i]] != -1)
start = max(start, hash[s[i]] + 1); //设置字符串起始位置
maxlength = max(maxlength, i - start + 1);
hash[s[i]] = i; //记录字符最后一次出现的位置
}
return maxlength;
}
};