力扣3. 无重复字符的最长子串

 

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         int left = 0, right = 0;
 5         int start = 0, len = 0;
 6         int repeat = 0; //记录重复元素个数
 7         unordered_map<int, int> window;
 8         while(right < s.size()) {
 9             window[s[right]]++;
10             if (window[s[right]] == 2) {repeat++;} // 一定要window[s[right]] == 2而不是window[s[right]] >= 2(这样写会重复计数)
11             right++;
12             while(repeat > 0) { //一旦有重复元素,左界就开始收缩,直到没有重复元素为止
13                 if (window.count(s[left])) {
14                     if (window[s[left]] == 2) {repeat--;}  
15                     window[s[left]]--;
16                 }
17                 left++;
18             }
19             len = max(right - left, len);
20         }
21         return len;
22     }
23 };

 巧思:使用record数组直接记录当前字符最后一次出现的位置(的下一个位置)

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         unordered_map<char, int> record; // 记录当前字符的下一个字符的位置
 5         int res = 0;
 6         for (int left = 0, right = 0; right < s.size(); ++right) {
 7             left = max(record[s[right]], left); //如果record[s[right]]!=0,说明s[right]已经出现过,如果此时左边界在圈外,则收缩
 8             record[s[right]] = right + 1; // 更新s[right]最新位置的下一个位置
 9             res = max(right - left + 1, res);
10         }
11         return res;
12     }
13 };

 

posted on 2025-03-04 19:06  Coder何  阅读(8)  评论(0)    收藏  举报