Given a string s
, your task is to find the length of the longest substring that contains no repeating characters.
If the string is empty, return 0
.
For example:
Input:
s = "abcabcbb" → Output:
3 (The answer is "abc")
#include <stdio.h>
#include <string.h>
int lengthOfLongestSubstring(char* s) {
int lastIndex[256];
for (int i = 0; i < 256; i++) lastIndex[i] = -1;
int maxLen = 0, start = 0;
for (int i = 0; s[i] != '\0'; i++) {
unsigned char ch = s[i];
if (lastIndex[ch] >= start) {
start = lastIndex[ch] + 1;
}
lastIndex[ch] = i;
int windowLen = i - start + 1;
if (windowLen > maxLen) maxLen = windowLen;
}
return maxLen;
}
int main() {
char s[] = "abcabcbb";
int result = lengthOfLongestSubstring(s);
printf("Length of longest substring without repeating characters: %d\n", result);
return 0;
}
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | In the best case, where all characters are unique, the algorithm still needs to traverse each character once, updating the map and window size. Thus, the time complexity remains linear. |
Average Case | O(n) | Each character is processed at most twice: once when added to the hash map and possibly again when the window start is moved. Hence, the total operations are proportional to the string length. |
Worst Case | O(n) | In the worst case, such as when the string contains all unique characters or repeated patterns forcing frequent updates to the start pointer, each character is still visited at most twice, making the time complexity linear. |
Comments
Loading comments...