> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/3.-longest-substring-without-repeating-characters.md).

# 3. Longest Substring Without Repeating Characters

## 1.問題

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

![](/files/-LJDIcBYkbN81ovtqFDe)

## 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

![](/files/-LJDItV1yWwdnNcMdC6J)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
