Responsive Ads Here

Tuesday, 2 May 2017

Remove duplicate characters from a string in O(N) time complexity.

Remove duplicate elements from a string in efficient way!

#include<iostream>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
    {
    char str[1005];// Max length of input string
    bool hash[256]={0}; //this is used for memotization 
    cin.ignore();
    scanf("%[^\n]s",str);// scanset is used to read string till nextline character.
    int i=0,j=0;
    while(str[i]!='\0')
        {
        if(!hash[str[i]]) //check if element is never present before in the string
            str[j]=str[i],hash[str[i]]=1,++j;
        i++;
        }
    str[j]='\0';//put this chacter to end the string at jth character
    printf("%s",str);
    }
return 0;
}

No comments:

Post a Comment