3. Longest Substring Without Repeating Characters**
https://leetcode.com/problems/longest-substring-without-repeating-characters/
题目描述
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.
C++ 实现 1
使用双指针+哈希表. 保持 s[j, i)
范围内的字符是 unique 的. 每访问一个字符 s[i]
, 便将它加入到哈希表中, 当再遇到新的字符时, 判断哈希表中是否已经存在该字符了, 如果存在, 移动 j
指针, 并不断将 s[j]
从哈希表中删除.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> record;
int res = 0;
int i = 0, j = 0;
while (i < s.size()) {
if (!record.count(s[i])) record.insert(s[i++]);
else record.erase(s[j++]);
res = std::max(res, i - j);
}
return res;
}
};
C++ 实现 2
哈希表也可以使用数组来实现:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int record[256] = {0};
int i = 0, j = 0, res = 0;
while (j < s.size() && i <= j) {
if (record[s[j]] == 0)
record[s[j++]] ++;
else
record[s[i++]] --;
res = max(res, j - i);
}
return res;
}
};