Sunday, 13 July 2014

Arrays and Strings : Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not.



#include<iostream.h>
#include<conio.h>
#include<cstring.h>
string remove(string s)
{
    int len = s.length();
    if(len < 2) return s;
    string str = "";
    for(int i=0; i<len; ++i)
    {
        if(s[i] != '\0')
        {
            str += s[i];
            for(int j=i+1; j<len; ++j)
                if(s[j]==s[i])
                    s[j] = '\0';
        }
    }
    return str;
}
int main ()
{
  string s1 = "abcdefgha" ;
  cout<<remove(s1) ;
  getch();
}

In this code we pick a character from the string assign it and then compare every Ith character with each and every I+1th character till the last character if we encounter a match we null that position .
In the end we return the string
 

No comments:

Post a Comment