美文网首页
LeetCode #3 Longest Substring Wi

LeetCode #3 Longest Substring Wi

作者: 刘煌旭 | 来源:发表于2021-04-21 18:23 被阅读0次
    Longest_Substring.png
    /**
    * This is an improved version over the previous submission: https://www.jianshu.com/p/56eac9b1f73c
    */
    
    void clear(int *a, char *s, int start, int end) { for (int i = start; i <= end; i++) { a[s[i]] = -1; } }
    
    #define R 128//capacity of the character set
    int lengthOfLongestSubstring(char * s) {
        if (s == NULL || *s == '\0') return 0;
        int n = strlen(s);
        int *a = (int*)malloc(R * sizeof(*a));
        for (int i = 0; i < R; i++) { a[i] = -1; }
        int len = 0, start = 0;
        for (int i = 0; i < n; i++) {
            if (a[s[i]] != -1) {
                int t = i - start;
                if (len < t) { len = t; }
                start = a[s[i]] + 1;
                clear(a, s, i - t/*i - t = start*/, a[s[i]]);
            }
            a[s[i]] = i;
        }
        int t = n - start;
        if (len < t) { len = t; }
        return len;
    }
    

    相关文章

      网友评论

          本文标题:LeetCode #3 Longest Substring Wi

          本文链接:https://www.haomeiwen.com/subject/qjbzlltx.html