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.
算法思路:
配合map的双指针技术
class Solution {//slide window O(n) O(1) 8ms
public:
int lengthOfLongestSubstring(string s) {
int n=s.size();
if(n==0 || n==1) return n;
int freq[256]={0}; //set的作用
int l=0,r=0; //[l...r]没有重复子串
int res=0;
while(l<n && r<n){
if(freq[s[r]]==0){
freq[s[r++]]++;
res=max(res,r-l);
}else freq[s[l++]]--;
}
return res;
}
};
The above solution requires at most 2n steps. In fact, it could be optimized to require only n steps. Instead of using a set to tell if a character exists or not, we could define a mapping of the characters to its index. Then we can skip the characters immediately when we found a repeated character.
The reason is that if s[r] have a duplicate in the range [l, r) with index r', we don't need to increase l little by little. We can skip all the elements in the range [l, r'] and let l to be r' + 1 directly.
class Solution {//slide window O(n) O(1) 8ms,前一个算法真实时间复杂度是O(2n)
public:
int lengthOfLongestSubstring(string s) {
int n=s.size();
if(n==0 || n==1) return n;
int index[256]={0}; //改变使之成为map的作用,记录该元素的位置,即角标值+1,区分0,0表示没有
int l=0,r=0; //[l...r]没有重复子串
int res=0;
while(r<n){
l=max(index[s[r]],l);
res=max(res,r-l+1);
index[s[r]]=r+1;
r++;
}
return res;
}
};
扩展:
Java (Assuming ASCII 128)
The previous implements all have no assumption on the charset of the string s
.
If we know that the charset is rather small, we can replace the Map
with an integer array as direct access table.
Commonly used tables are:
int[26]
for Letters 'a' - 'z' or 'A' - 'Z'int[128]
for ASCIIint[256]
for Extended ASCII
参考资料:
https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/