# 无重复字符的最长子串

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

 

示例 1:

输入: s = "abcabcbb"
输出:
3
解释:
因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:

输入: s = "bbbbb"
输出:
1
解释:
因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:

输入: s = "pwwkew"
输出:
3
解释:
因为无重复字符的最长子串是 "wke",所以其长度为 3。  请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

示例 4:

输入: s = ""
输出:
0

 

提示:

以下错误的选项是?

## aop ### before ```c #include using namespace std; ``` ### after ```c int main() { Solution test; int ret; string s = "bbbbb"; ret = test.lengthOfLongestSubstring(s); cout << ret; return 0; } ``` ## 答案 ```c class Solution { public: int lengthOfLongestSubstring(string s) { int count = 0; int i = 0, j = 1, p1 = 0, p2 = 0; if (s.length() == 0) return 0; else { count = 1; while (s[j] != '\0') { for (int i = p1; i <= p2; i++) { if (s[i] == s[j]) { p1 = i + 1; break; } } p2 = j; count = count >= (p2 - p1 + 1) ? (p2 - p1 + 1) : count; j++; } } return count; } }; ``` ## 选项 ### A ```c class Solution { public: int lengthOfLongestSubstring(string s) { map hash; int ans = 0; int n = s.size(); for (int i = 0, j = 0; j < n; j++) { if (hash.find(s[j]) != hash.end()) i = max(hash.find(s[j])->second + 1, i); ans = max(ans, j - i + 1); hash[s[j]] = j; } return ans; } }; ``` ### B ```c class Solution { public: int lengthOfLongestSubstring(string s) { map hash; int ans = 0; int i = 0; int j = 0; int n = s.length(); while (i < n && j < n) { if (hash.find(s[j]) == hash.end()) { hash[s[j++]] = j; ans = max(ans, j - i); } else hash.erase(s[i++]); } return ans; } }; ``` ### C ```c class Solution { public: int lengthOfLongestSubstring(string s) { int ans = 0; for (int i = 0; i < s.size(); i++) for (int j = i + 1; j <= s.size(); j++) { if (allUnique(s, i, j)) ans = max(ans, j - i); } return ans; } bool allUnique(string s, int begin, int end) { map hash; for (int i = begin; i < end; i++) { if (hash.find(s[i]) != hash.end()) return false; hash[s[i]] = i; } return true; } }; ```