LeetCode Longest Substring Without Repeating Characters

LeetCode Longest Substring Without Repeating Characters

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.

```class Solution {
public:
int lengthOfLongestSubstring(string s) {
int longest = 0, n = s.size(), cur = 0;
vector<int> hash(128, 0);
for (int i = 0; i < n; i++)
{
if (hash[s[i]])
{
if (cur > longest)
longest = cur;
cur = 0;
i = hash[s[i]];//从重复字符下一个字符开始遍历
//memset(&hash[0], 0, 128*sizeof(int));//比fill更快，但是没fill安全
fill(hash.begin(), hash.end(), 0);
}
hash[s[i]] = i + 1;//记录下一个字符下标
cur++;
}
return (longest > cur) ? longest : cur;
}
};
```

```class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char, int> visited;
int ans = 0, start = -1;
for (int i = 0; i < s.size(); ++i) {
if (visited.find(s[i]) != visited.end())
start = max(start, visited[s[i]]);
visited[s[i]] = i;
ans = max(ans, i - start);
}
return ans;
}
};
```