19.1.11 LeetCode 3 Longest Substring Without Repeating Characters

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.
 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         int len = 0,st=0,ed=0;
 5         set<char>q;
 6         for (int i = 0; s[i]; i++) {
 7             set<char>::iterator i1 = q.find(s[i]);
 8             if (i1 != q.end()) {
 9                 len = max(len, ed - st );
10                 while (s[st] != s[i]) {
11                     q.erase(q.find(s[st]));
12                     st++;
13                 }
14                 q.erase(q.find(s[st]));
15                 st++;
16             }
17             q.insert(s[i]);
18             ed++;
19         }
20         len = max(len, ed - st );
21         cout << len << endl;
22         return len;
23     }
24 };
View Code

滑动窗口,看题解最优化的解法是在这个方案的基础上把遇到重复字符时一个个增加头指针位置换成直接跳到重复字符之后。

注定失败的战争,也要拼尽全力去打赢它; 就算输,也要输得足够漂亮。
原文地址:https://www.cnblogs.com/yalphait/p/10255213.html