Description
Given a string, find the length of the longest substring without repeating characters.
Example
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.
Solution
1 | class Solution { |
Solution 1
First set the first element as the current longest substring
For the rest part of the input string, check if each element is in the substring
If not, plus one to current temp length value
If yes, reset the current longest substring from the index where the element occurs last time and reset the temp length value
Each time, comparing the current temp length with the final length
1 | class Solution: |
Solution 2
Using a list to record where each letter occurs, -1 for each one for initialization.
Using a value First to record the begining of current longest substring, -1 as initialization.
Looping the string, if the index where the element occurs bigger than the value First, meaning that the element has occurs in current substring, then renew the First and store the element’s current index. Renew the count of length at last
1 | class Solution: |