LeetCode //C - 3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring without repeating characters.

 

Example 1:

Input: s = “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.

Example 2:

Input: s = “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.

Example 3:

Input: s = “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Notice that the answer must be a substring, “pwke” is a subsequence and not a substring.

Constraints:

  • 0 < = s . l e n g t h < = 5 ∗ 1 0 4 0 <= s.length <= 5 * 10^4 0<=s.length<=5104
  • s consists of English letters, digits, symbols and spaces.

From: LeetCode
Link: 3. Longest Substring Without Repeating Characters


Solution:

Ideas:
This function uses a sliding window to find the longest substring without repeating characters. The for loop iterates through the string. If a character is repeated (has been seen before), the left pointer of the window is moved right to the next character after the repeated one. The variable res keeps track of the maximum length of such a substring seen so far. Finally, the function returns res, which is the length of the longest substring without repeating characters.
Code:
int lengthOfLongestSubstring(char *s) {
    int n = strlen(s);
    int res = 0; // result
    int seen[256];
    
    for (int i = 0; i < 256; i++) {
        seen[i] = -1; // -1 indicates that character has not been seen yet
    }
    
    int left = 0;
    
    for (int right = 0; right < n; right++) {
        // If the current character has been seen before, then update the left pointer
        if (seen[s[right]] >= left) {
            left = seen[s[right]] + 1;
        }
        
        // Update the result if needed
        res = res > right - left + 1 ? res : right - left + 1;
        
        // Mark the character as seen
        seen[s[right]] = right;
    }
    
    return res;
}

你可能感兴趣的:(LeetCode,leetcode,c语言,算法)