# 3. Longest Substring Without Repeating Characters

## 1.問題

* 給予一個string, 找出最長的沒有重複字元的substring

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJDEYcFwJuU7Pa6wKko%2F-LJDIcBYkbN81ovtqFDe%2F2018080601.jpg?alt=media\&token=1081f518-9e3f-4d65-9383-7e5e82f2bb9a)

## 2.想法

* 用vector來記錄曾經碰到過的字元, 一旦碰到第二次則將從start開始的紀錄取消並且寫入新的紀錄, 移動start, 紀錄長度為start到當前位置的長度
* 用vector代替map存放字母出現次數的好處是: 將會依照字母順序
* 對字串中每個子母進行標記: 出現兩次則清空, 並將first移到第一個重複字的下一個字母

## 3.程式碼

```
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> cnt(128, 0);
        int first = 0, size = s.size(), maxSize = 0;
        for (int i = 0; i < size; i++) {
            cnt[s[i]]++;
            if (cnt[s[i]] > 1) {
                //重要: 將first移動到第一個重複字出現的下一個字母
                for (; s[first] != s[i]; first++) {
                    cnt[s[first]] = 0;
                }
                first++;
            }
            maxSize = max(i - first + 1, maxSize); 
        } 
        return maxSize;
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJDEYcFwJuU7Pa6wKko%2F-LJDItV1yWwdnNcMdC6J%2F2018080602.jpg?alt=media\&token=74cc7031-e474-4cd8-a64f-d99ad40563a9)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/3.-longest-substring-without-repeating-characters.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
