Remove Duplicates from an Unsorted Sring
PROBLEM :
Given a string, remove duplicates from it. Note that original order of characters must be kept same. Expected time complexity O(n) where n is length of input string and extra space O(1) under the assumption that there are total 256 possible characters in a string.
Input: First line of the input is the number of test cases T. And first line of test case contains a string.
Output: Modified string without duplicates and same order of characters.
Constraints: Input String Length <= 1000
Example:
Input:
2
geeksforgeeks
geeks for geeks
Output:
geksfor
geks for
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
#include<string.h>
char * Remove_Duplicates(char *) ;
int main()
{
int t ;
char *str ;
str=(char*)malloc(1000*sizeof(char)) ;
cin>>t ;
while(t--)
{
scanf(" %[^\n]s",str) ;
str=Remove_Duplicates(str) ;
cout<<str<<endl ;
}
return 0;
}
char * Remove_Duplicates(char *str)
{
int hash[256]={0} ;
int i,l,k ;
l=strlen(str) ;
k=0 ;
for(i=0;i<l;i++)
hash[str[i]]=1 ;
for(i=0;i<l;i++)
{
if(hash[str[i]]==1)
{
str[k]=str[i] ;
k++ ;
hash[str[i]]=0 ;
}
}
str[k]='\0' ;
return str ;
}
---------------------------------------------------------------------------------
Given a string, remove duplicates from it. Note that original order of characters must be kept same. Expected time complexity O(n) where n is length of input string and extra space O(1) under the assumption that there are total 256 possible characters in a string.
Input: First line of the input is the number of test cases T. And first line of test case contains a string.
Output: Modified string without duplicates and same order of characters.
Constraints: Input String Length <= 1000
Example:
Input:
2
geeksforgeeks
geeks for geeks
Output:
geksfor
geks for
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
#include<string.h>
char * Remove_Duplicates(char *) ;
int main()
{
int t ;
char *str ;
str=(char*)malloc(1000*sizeof(char)) ;
cin>>t ;
while(t--)
{
scanf(" %[^\n]s",str) ;
str=Remove_Duplicates(str) ;
cout<<str<<endl ;
}
return 0;
}
char * Remove_Duplicates(char *str)
{
int hash[256]={0} ;
int i,l,k ;
l=strlen(str) ;
k=0 ;
for(i=0;i<l;i++)
hash[str[i]]=1 ;
for(i=0;i<l;i++)
{
if(hash[str[i]]==1)
{
str[k]=str[i] ;
k++ ;
hash[str[i]]=0 ;
}
}
str[k]='\0' ;
return str ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment