【Leetcode】3. Longest Substring Without RepeatingCharacters無重最長子串

knzeus發表於2019-05-14

1. 題目

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, 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.

https://leetcode.com/problems…

2. 思路

遍歷計算s[i:j]的以i為起點的最長j,通過hashset判重來計算是否獨立。找到一個最大的j之後,計算當前找到的以i為起點的是不是更大值,是則保持。然後衝i開始往後跳躍到等於s[j+1]字元的位置的下一個位置作為新的i起點。跳躍時經過的字元從hashset中清除。
整體複雜度是O(N)

3. 程式碼

耗時:16ms

#include <string>
//#include <unordered_set>

class HashSet {
public:
    HashSet() {
        clear();
    }
    void clear() {
        for (int i = 0; i < 256; i++) {
            _s[i] = false;
        }
    }
    bool has(char c) {
        return _s[c + 128];
    }
    bool insert(char c) {
        int i = c + 128;
        bool ret = _s[i];
        _s[i] = true;
        return ret;
    }
    void erase(char c) {
        _s[c + 128] = false;
        return ;
    }
    
private:
    bool _s[256];
};

class Solution {
public:
    int lengthOfLongestSubstring(const string& s) {
        h.clear();
        int i = 0; 
        int j = 0;
        int len = s.length();
        int max = 0;
        int max_i = 0;
        while (i < len - max && j < len) {
            char cj = s[j];
            //if (h.insert(cj).second) {
            if (!h.insert(cj)) {
                ++max_i;
                ++j;
                continue;
            }
            if (max_i > max) {
                max = max_i;
            }
            while (i < j + 1) {
                char ci = s[i];
                h.erase(ci);
                --max_i;
                if (ci != cj) {
                    ++i;
                } else {
                    ++i;
                    break;
                }
            }
        }
        if (max_i > max) {
            max = max_i;
        }
        return max;
    }
    
private:
//    std::unordered_set<char> h;
    HashSet h;
};

相關文章