longest substring
Examples:
"abcabcbb"
, the answer is "abc"
, which the length is 3."bbbbb"
, the answer is "b"
, with the length of 1."pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence
Subscribe to see which companies asked this question
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.empty()) return 0;
if (s.size() == 1) return 1;
vector<int> hash(256, -1);
int i = 0, j = 1;
int res = 0;
hash[s[0]] = 0;
while (j<s.size()){
if (hash[s[j]] >= i){
i = hash[s[j]] + 1;
}
hash[s[j]] = j;
res = max(res, j - i + 1);
j++;
}
return res;
}
};