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.
Idea:
Using a dictionary to keep track of the index of last appearance of a letter, then set a window with left and right boundry. The initial valut of left is -1 and the right is the index that goes throught the string. I used a enumaration to go therough the given string (the enumatre() function returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence). During each loop, the left equals to the max value between the origin left and the value of map[charactor]. The vaule of rigth minus left is the max result of longgest substring without repeating characters.
我们创建一个字典来记录每个字符在字符串中最近发生的情况。我们有一个左右标记来创建我们感兴趣的窗口。我们保证右总是大于左,所以当执行左-右时,如果左永远没有更新,它会向右索引添加1。当左可能更新时,右-左将给我们更新窗口的长度。
func lengthOfLongestSubstring(_ s: String) -> Int {
var map = [Character:Int]()
var result = 0
var left = -1
for (right, char) in s.enumerated(){
left = max(left,map[char] ?? -1)
result = max(result, right - left)
map[char] = right
}
return result
}