其他分享
首页 > 其他分享> > Lc3无重复最长字串

Lc3无重复最长字串

作者:互联网

在这里插入图片描述
链接:无重复最长字串

步骤:
定义两个指针i,j 表示当前扫描到的字串是[i,j] (闭区间)扫描过程中维护一个哈希表unordered_map<char,int> hash 表示[i, j] 中每个字符出现的次数、

  1. 指针j 向后移动一位,同时将哈希表中s[j] 的次数 +1 hash[s[j]] ++
  2. 假设j移动的当前区间[i, j] 中没有重复字串, 一旦j 移动后那么只有s[j] 出现了2次,不断移动i直到区间中s[j]的个数等于1为止。

时间复杂度:O(n)

int lengthOfLongestSubstring(string s) {
    unordered_map<char, int> hash;
    int res = 0;
    for (int i = 0, j = 0; j < s.size(); j ++) {
        hash[s[j]] ++;
        while(hash[s[j]] > 1) hash[s[i ++]] --;
        res = max(res, j - i + 1);
    }
    return res;
}

在这里插入图片描述

在这里插入图片描述

let map = new Map(), max = 0;
for (let i = 0, j = 0; j < s.length; j ++) {
      if (map.has(s[j])) {
          i = Math.max(map.get(s[j]) + 1, i);
      }
      max = Math.max(max, j - i + 1);
      map.set(s[j], j);
  }
  return max;

标签:map,hash,Lc3,++,max,字串,res,最长
来源: https://blog.csdn.net/weixin_43509985/article/details/118002430