leetcode-3. Longest substring without repeating characters

Posted by zildjohn01 on Thu, 14 May 2020 16:09:18 +0200

leetcode-3. The longest substring without repeating characters.

Given a string, please find out the length of the longest substring that does not contain duplicate characters.

Example 1:

Type: "abcabcbb"
Output: 3
 Explanation: because the longest substring without repeating characters is "abc", its length is 3.

Example 2:

Enter: "bbbbb"
Output: 1
 Explanation: because the longest substring without repeating characters is "b", its length is 1.

Example 3:

Enter: "pwwkew"
Output: 3
 Explanation: because the longest substring without repeating characters is "wke", its length is 3.
Note that your answer must be the length of the substring, "pwke" is a substring, not a substring.

Source: LeetCode
Link: https://leetcode-cn.com/problems/two-sum
Copyright belongs to the network. For commercial reprint, please contact the official authorization. For non-commercial reprint, please indicate the source.



Solution 1: violence cycle + HashTable or HashMap.
#define MAX( a, b ) ((a) > (b) ? (a) : (b))

int lengthOfLongestSubstring( char *s ) {
	int i = 0, j = 0, count = 0, answer = 0;
	int map[128] = {0};

	for( i = 0; s[i] != '\0'; ++i ) {
		count = 0;
		for( j = i; s[j] != '\0' && !map[s[j]]; ++j ) {
			++count;
			map[s[j]] = 1;
		}
		answer = MAX( answer, count );
		for( j = 0; j < sizeof(map) / sizeof(*map); ++j ) {
			map[j] = 0;
		}
	}

	return answer;
}


Solution 2: sliding window + HashTable or HashMap.
#define MAX( a, b ) ((a) > (b) ? (a) : (b))

int lengthOfLongestSubstring( char *s ) {
	int answer = 0, map[128] = {0};
	int windowL = 0, windowR = 0;
	int slen = strlen( s );

	for( windowL = windowR = 0; windowR < slen; ++windowR ) {
		if( map[s[windowR]] > windowL ) {  // Update the left border of the window
			windowL = map[s[windowR]]; // Keep windows heterogeneous (that is, any two elements in a window are different)
		}
		map[s[windowR]] = windowR + 1;     // The next position of the current position
		answer = MAX( answer, windowR - windowL + 1 );
	}

	return answer;
}

// Make a small optimization to eliminate the strlen function call
int lengthOfLongestSubstring( char *s ) {
	int answer = 0, map[128] = {0};
	int windowL = 0, windowR = 0;

	for( windowL = windowR = 0; s[windowR] != '\0'; ++windowR ) {
		if( map[s[windowR]] > windowL ) {  // Update the left border of the window
			windowL = map[s[windowR]]; // Keep windows heterogeneous (that is, any two elements in a window are different)
		}
		map[s[windowR]] = windowR + 1;     // The next position of the current position
		answer = MAX( answer, windowR - windowL + 1 );
	}

	return answer;
}



Topics: C Windows network