Saturday, October 3, 2015

[1.3] Remove the duplicate characters in a String

1. Example

s= "abcd"
s= null
s= ""
s= "aaaa"
s= "aabb"

NOTE :without using any additional buffer

2. Implementation


// Time :O(n^2) , Space:O(1)
// Keep a new Index with all unique characters, and every incoming 
// character need to check with them

public static void removeDuplicate( char[] str)
{
 
   

     //validate the input
     if ( str == null )
        return;
     int len = str.length;
     if ( len < 2 )
       return;




     int tail =1;
     for (int i =1; i < len; ++i)
     {
        int j;



        // NOTE: compare with new string with all unique characters
        for (j = 0 ; j < tail; ++j)
        {
            
            if ( str[i] == str[j] )
                  break;
        }



        // NOTE: it is a unique one
        if ( j == tail )
        {
            str[tail] = str[i];
            ++tail;
        } 
 


     }



     // NOTE: last null character
     str[tail] = 0;



}


// Time :O(n), Space:O(1)[256]
// Assume all ASCII characters
public static void removeDuplicate(char[] str)
{

        
      
    // validate the input
    if (str == null)
         return;
    int len = str.length;
    if (len < 2)
         return;





    boolean[] hit = new boolean[256];
    for (int i = 0 ; i < 256; ++i)
    {
         hit[i] = false;
    }



   
    hit[str[0]] = true;



    
    int tail = 1; 
    for (int i =1; i < len; ++i)
    {
         if ( !hit[str[i]] )
         {
            str[tail] = str[i];
            ++tail;
            hit[str[i]] = true;
         }
    }




    str[tail] = 0;



}
3. Similar ones



No comments:

Post a Comment