Get Off-Campus Placement Jobs Info !!!
Programs asked in Mettl Coding Round
Click To Practce List of Programs asked in Nagarro !!!

Program Discussion :: Strings

Home > Programs > Strings

2 / 59

Write a program to find the largest substring of a given string without repeating characters.

Answer:

#include
#include
#include
#include 
using namespace std;
#define NO_OF_CHARS 256
int min(int a, int b);
int longestUniqueSubsttr(char *str)
{
    int n = strlen(str);
    int cur_len = 1; /*lenght of current substring*/
    int max_len = 1; /* result*/
    int prev_index; /* previous index*/
    int i;
    int *visited = (int *)malloc(sizeof(int)*NO_OF_CHARS);
    for (i = 0; i < NO_OF_CHARS; i++)
        visited[i] = -1;
    visited[str[0]] = 0;
    for (i = 1; i < n; i++)
    {
        prev_index = visited[str[i]];

        if (prev_index == -1 || i - cur_len > prev_index)
            cur_len++;

        else
        {
    
            if (cur_len > max_len)
                max_len = cur_len;

            cur_len = i - prev_index;
        }
        visited[str[i]] = i;
    }

    
    if (cur_len > max_len)
        max_len = cur_len;

    free(visited); // free memory allocated for visited
    return max_len;
}

int min(int a, int b)
{
    return (a>b)?b:a;
}

int main()
{
    char str[] = "ABDEFGABEF";
    cout

Asked In :: Aricent

Post Your Answer Here:

Language:

Post Your Reply Here:



Language:

Post Your Reply Here: