Leetcode: 3.Longest Sub-string Without Repeating Characters 无重复字符的最长子串

Longest Sub-string Without Repeating Characters 无重复字符的最长子串

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。


输入:

"abcabcbd"

输出:

3

因为无重复字符的最长子串是 “abc”,所以其长度为 3。


方法一:HashMap+滑动窗口
遍历每个字符s[i],用HashMap存储字符出现的位置,并查找之前是否已经出现过。始终更新最大长度。

class Solution{
    public:
     int lengthOfLongestSubstring(string s) {
        int res=0,left=-1,n=s.size();
        unordered_map<int,int>m;
        for(int i=0;i<n;i++){
            if(m.count(s[i])&&m[s[i]]>left)
                left=m[s[i]];//更新
            m[s[i]]=i;//存储字符出现位置
            res=max(res,i-left);
        }
        return res;
    }
};

时间复杂度:O(n)

空间复杂度:O(n)


方法二:Set
用set来去重

class Solution {
public:
    int lengthOfLongestSubstring(string s)  {
        int res=0,left=0,i=0,n=s.size();
        unordered_set<char>t;
        while(i<n){
            if(!t.count(s[i])) {
                t.insert(s[i++]);
                res=max(res,(int)t.size());
            }
            else t.erase(s[left++]);//删除左边的字符直到删到重复的位置
        }
        return res;
    }
};

复杂度分析:

时间复杂度:O(n)
空间复杂度:O(n)


相关标签:
哈希表 双指针 字符串 滑动窗口


相似题目:
至多包含两个不同字符的最长子串
至多包含 K 个不同字符的最长子串
K 个不同整数的子数组


你可能感兴趣的:(Leetcode刷题记录)