题目:
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, 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.
思路:
典型的字符串问题中的“Two Pointers”的应用。可以借助一个hash表,维护一个不包含重复字符串的窗口,使用左右指针left,right滑动窗口大小。左右指针的滑动规则如下:
1)首先右指针right向右移动,直到遇到一个和窗口中有重复的字符。右指针在滑动过程中更新最大不重复子串的长度。
2)此时左指针向右移动到重复字符之后去,同时更新hash表中的字符。
该算法的时间复杂度为O(n),空间复杂度依然为O(n)。
在面试中需要注意英文中“subsequence”和“substring”的区别。前者中的邻接字符在原串中也必须是邻接的,而后者中的邻接字符在原串中未必需要邻接。
代码:
C++:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.size() == 0)
return 0;
int left = 0, right = 0, max_length = 0;
unordered_map<char, bool> hash;
for(right = 0; right < s.size(); ++right)
{
while(hash.count(s[right]))
hash.erase(s[left++]);
hash[s[right]] = true;
max_length = max(max_length, (int)hash.size());
}
return max_length;
}
};
Python3:
class Solution:
def lengthOfLongestSubstring(self, s: 'str') -> 'int':
if len(s) == len(set(s)): # this means every charchater is unique
return len(s)
d = {} # map from values to indices
start = 0
tmp = 0
ans = 0
for index, val in enumerate(s):
if val in d and d[val]>= start:
start = d[val] + 1
d[val] = index
tmp = index - start + 1
ans = max(ans,tmp)
return ans