Problem:
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.
Constraints:
0 <= s.length() <= 5 * 10^4
Approach:
This problem can be solved using the "Two Pointers" method. Now the question is how can we move our pointers. We have to think a little bit, we can't sort our string or we can't take two pointers from 2 sides (left and right).
See, we can start our both pointers from starting position, every time we will increase one pointer, then if we met the current character before, then another pointer will be updated by the previous position of the current character. Okay, let's try to visualize,
left = previous position + 1.
See the Code for a better understanding.
Time Complexity: O(n)See the Code for a better understanding.
Space Complexity: O(1)
No comments:
Post a Comment