leetcode-3:无重复字符的最长子串

int check(char* s, int l) {
    int cnt[300] = { 0 }, k = 0;
    for (int i = 0; s[i]; i++) {
        cnt[s[i]] += 1;
        if (cnt[s[i]] == 1) k++;
        if (i >= l){
            cnt[s[i - l]] -= 1;
            if (cnt[s[i - l]] == 0) k--;
        }
        if (k == l) return 1;
    }
    return 0;
}

int lengthOfLongestSubstring(char * s){
    int head = 0, tail = strlen(s), mid;
    while (head < tail) {
        mid = (head + tail + 1) / 2;
        if (check(s, mid)) head = mid;
        else tail = mid - 1;
    }
    return head;
}

你可能感兴趣的:(算法题,leetcode,算法)