Longest Substring Without Repeating Characters

思考:通过自建哈希集合的方法来实现滑动窗口
未优化:

class MyHashSet {
public:
    /** Initialize your data structure here. */
    vector<bool> hash;
    MyHashSet() {
        hash = vector<bool>(1000001, false);
    }
    
    void add(int key) {
        hash[key] = true;
    }
    
    void remove(int key) {
        if(hash[key])
        {
            hash[key] = false;
        }
        return;
    }
    /** Returns true if this set contains the specified element */
    bool contains(int key) {
        if(hash[key])
        {
            return true;
        }
        return false;
    }
};
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int len = s.length();
        MyHashSet hashSet ;//滑动窗口
        int i=0;//滑动窗口左端
        int j=0;//滑动窗口右端
        int ans=0;
        while(i<=j&&j<len)
        {
            if(!hashSet.contains(s[j]))
            {
                ans=max(j-i+1,ans);
                hashSet.add(s[j]);
                j++;
            }else{
                hashSet.remove(s[i]);
                i++;
            }
        }
        return ans;
    }
};

你可能感兴趣的:(LeetCode,基础编程练习)