changed 4 years ago
Linked with GitHub

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.
    
  • Example 4:
    ​​  Input: s = ""
    ​​  Output: 0
    
  • Constraints:
    ​​​​0 <= s.length <= 5 * 104
    ​​​​s consists of English letters, digits, symbols and spaces.
    

C

#include <stdlib.h> #include <stdio.h> //3. Longest Substring Without Repeating Characters int lengthOfLongestSubstring(char* s) { int max = 0; int temp_max = 0; int current = 0; int repeating_char = 0; int new_start = 0; int flag = 0; if (s[current] == '\0') return 0; while (s[current] != '\0') { for (repeating_char = current - 1; repeating_char >= new_start; repeating_char--) { if (s[repeating_char] == s[current]) { flag = 1; break; } } if (flag == 0) { temp_max++; } else { new_start = repeating_char + 1; temp_max = current - new_start + 1; flag = 0; } if (temp_max > max) max = temp_max; current++; } return max; } void main() { //3. Longest Substring Without Repeating Characters char* s = (char*)malloc(sizeof(char) * 10); s = "abcabcbb"; //printf("%s\n", s); printf("%d\n", lengthOfLongestSubstring(s)); }

C++

Select a repo