# 【LeetCode】 3. Longest Substring Without Repeating Characters
## 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
* 用map記錄每個字元最後出現的位置。
* 記錄最後一次有重複字元的位置 = last。
* 現在位置-last是該位置目前的最大長度。
### Code
```C++=1
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char,int> m;
int ans = 0;
int last = -1;
for(int i = 0;i<(int)s.size();i++)
{
if(m.find(s[i])!=m.end())
{
last = last > m[s[i]] ? last : m[s[i]];
}
ans = ans > (i-last) ? ans : (i-last);
m[s[i]]=i;
}
return ans;
}
};
```
###### tags: `LeetCode` `C++`