Skip to main content

Featured

Solve LeetCode 3 Longest Substring Without Repeating Characters in C++ using the sliding window

Longest Substring Without Repeating Characters in C++ LeetCode 3 · sliding window · last index array Table of Contents Problem Statement Approach Algorithm C++ Program Input Sample Output Output Explanation Dry Run Flow of Execution Time Complexity Space Complexity Applications Key Points Interview Questions Frequently Asked Questions Conclusion Problem Statement 3. Longest Substring Without Repeating Characters Given a string s , find the length of the longest substring that contains no repeating characters. A substring is a continuous part of the string, so "pwke" is a subsequence of "pwwkew" but not a substring. Approach We use a sliding window . The window is the part of the string between start and end , and we always keep it free of repeated characters. An array lastIndex of size 128 remembers the most recent position of every ASCII ...

C Program to Remove Duplicates, Ignore Spaces, and Sort Characters in Descending Order

Remove Duplicates and Sort Characters in Descending Order - C Program

๐Ÿš€ C Program to Remove Duplicates, Ignore Spaces, and Sort Characters in Descending Order

๐Ÿ“„ Source Code:


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

int present(char a[], char ch, int len)
{
    for (int i = 0; i < len; i++)
    {
        if (a[i] == ch)
        {
            return 1;
        }
    }
    return 0;
}

void des(char a[], int len)
{
    for (int i = 0; i < len - 1; i++)
    {
        for (int j = i + 1; j < len; j++)
        {
            if (a[i] < a[j])
            {
                char temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
}

int main()
{
    char str[200], result[200];
    int j = 0;
    fgets(str, sizeof(str), stdin);
    int len = strlen(str);
    if (str[len - 1] == '\n')
    {
        str[len - 1] = '\0';
    }

    for (int i = 0; str[i] != '\0'; i++)
    {
        if (str[i] != ' ' && !present(result, str[i], j))
        {
            result[j++] = str[i];
        }
    }

    des(result, j);
    result[j] = '\0';

    printf("Resulting string: %s\n", result);
}
    

๐Ÿ“˜ Deep Explanation:

This C program performs three core operations on a string entered by the user:

  • ๐Ÿ”น 1. It removes duplicate characters from the string.
  • ๐Ÿ”น 2. It ignores spaces.
  • ๐Ÿ”น 3. It sorts the unique characters in descending order.
  • ๐Ÿ”ธ present() checks if a character is already in the result array.
  • ๐Ÿ”ธ des() uses a simple bubble sort in descending (Z to A) order.
  • ๐Ÿ”ธ fgets() is used instead of scanf() to read spaces.
  • ๐Ÿ”ธ Only unique characters are printed after sorting.

๐Ÿงช Sample Output:


Input:
Hello World

Output:
Resulting string: roledWH
    

Comments

Popular Posts

๐ŸŒ™