Python 2-pointer and dictionary


  • 0
    Z
    def lengthOfLongestSubstring(self, s):
        dic, res, start = {}, 0, 0
        for i, c in enumerate(s):
            start = max(start, dic.get(c,-1)+1) # advance start if necessary
            res = max(res, i-start+1) # update result
            dic[c] = i
        return res

  • 0
    S

    int max( int x, int y)
    {
    return x > y ? x : y;
    }

    int lengthOfLongestSubstring(char* s)
    {
    int i, j;
    int count;
    int n;
    int* st;

    if( s == NULL || *s == '\0' )
        return 0;
    
    n = strlen(s);
    st = (int*)malloc( sizeof(int) * n );
    for( i = 0; i < n; ++i )
        st[i] = 1;
    for( i = 1; i < n; ++i )
    {
        for( j = 1; j <= st[i-1]; ++j )
            if( s[i] == s[i-j] )
                break;
        st[i] = j > st[i-1] ? st[i-1] + 1 : j;
    }
    count = 1;
    for( i = 1; i < n; ++i )
        count = max( count, st[i] );
    free( st );
    
    return count;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.