w3resource

C Programming: Length of the longest substring in a given string

C String: Exercise-35 with Solution

Write a C program to find the length of the longest substring of a given string without repeating characters.

Sample Data:

(“aaaaaaaaa”) -> 1
(“abcddefffd” -> 4

Sample Solution:

C Code:

#include<stdio.h>
#include<string.h>

// Function to find the length of the longest substring without repeating characters
int test(char *str, int n) {
    int longest_str_len = 1;  // Length of the longest substring
    int current_substr_len = 1;  // Length of the current substring
    int previous_index, i;  // Variables for iteration
    int temp[256];  // Temporary array to store character indices

    memset(temp, -1, sizeof(int) * 256); // Initialize temp array with -1 (indicating no occurrence)

    temp[str[0]] = 0;  // Set the first character's index in the temp array

    for (i = 1; i < n; i++) {
        previous_index = temp[str[i]]; // Get the previous index of the character

        if (previous_index == -1 || i - current_substr_len > previous_index)
            current_substr_len++;  // If the character is not seen or not part of the current substring, increment the length
        else {
            if (current_substr_len > longest_str_len)
                longest_str_len = current_substr_len; // Update the longest substring length if current is greater

            current_substr_len = i - previous_index; // Update the length of the current substring
        }
        temp[str[i]] = i; // Update the index of the character
    }

    if (current_substr_len > longest_str_len)
        longest_str_len = current_substr_len; // Update the longest substring length if current is greater

    return longest_str_len; // Return the length of the longest substring without repeating characters
}

int main() {
    char str1[80]; // Declare string variable
    int n; // Variable to store string length

    printf("Input a string: ");
    scanf("%s",str1);
    n = strlen(str1); // Calculate the length of the input string

    if (n > 0) // If the length of the string is greater than zero
        printf("Length of the longest substring without repeating characters: %d", test(str1, n));

    return 0;
}

Sample Output:

 Input a string: “abcddefffd”
Input a string: Length of the longest substring without repeating characters: 4

Flowchart :

Flowchart: Length of the longest substring in a given string

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous C Exercise: Convert vowels into uppercase characters in a string.
Next C Exercise: Verify that a string contains valid parentheses.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.