Problem description:

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 sub-sequence and not a substring.

Solution:

Keep a hashmap which stores the characters in string as keys and their positions as values, and keep two pointers which define the max substring. move the right pointer to scan through the string , meanwhile update the hashmap. If the character is already in the hashmap, then move the left pointer to the right of the same character last found. Note that the two pointers can only move forward.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def lengthOfLongestSubstring(self, s):
start = maxLength = 0
usedChar = {}

for i in range(len(s)):
if s[i] in usedChar and start <= usedChar[s[i]]:
start = usedChar[s[i]] + 1
else:
maxLength = max(maxLength, i - start + 1)

usedChar[s[i]] = i

return maxLength
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.length() == 0) return 0;
unordered_map<char, int> map;
int maxl = 0, left= -1;
for(int i= 0; i< s.length(); i++){
if(map.find(s[i]) != map.end()){
//check whether if the character already in the map
left = max(map.find(s[i])->second, left); //if we can find, update the left pointer
}
map[s[i]] = i; //update the appearance position of the character in map
maxl = max(maxl, i-left); //max length would remain the same or (cur position-left pointer)
}
return maxl;
}
};

time complexity: O(n)

Solution2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int lengthOfLongestSubstring(string s) {
/*
use an unordered_map to store occurence of words
*/
unordered_map<char, int> map;
int start= 0, end= 0, res= 0;
while(end < s.length()){
char tmp= s[end];
map[tmp]++;
end++;
while(map[tmp] > 1){
map[s[start++]]--;
}
res= max(res, end- start);
}
return res;
}
};

reference:
https://goo.gl/mUhZjT
https://goo.gl/8cQL7W