Gaurav Juneja
Gaurav Juneja

Reputation: 1

Suggestions needed for the removal of characters from the String

I have written a program to remove the characters from the second string which are present in the first string.

I had Written a code for the above mentioned Problem Can someone Suggest Changes to make It efficient

class StrAssiQ5
{
  public static String Removal(String s,String s1)
  {
    StringBuffer a=new StringBuffer();;
    for(int i=0; i<s.length(); i++)
    {int count=0;
      for(int j=0; j<s1.length(); j++)
      {

        if(s.charAt(i)==s1.charAt(j))
        {
          count++;
        //a.append(Character.toString(s.charAt(i)));
        }
      }
      if (count==0)
      a.append(Character.toString(s.charAt(i)));
    }
    return a.toString();
  }
  public static void main(String [] args)
  {
    String s="Gaurav";
    String s1="Juneja";
    s=StrAssiQ5.Removal(s,s1);
    System.out.println(s);
  }
}

output is : Grv

Upvotes: 0

Views: 45

Answers (2)

Sıddık A&#231;ıl
Sıddık A&#231;ıl

Reputation: 967

The general rule of thumb in computer science for this type of list difference operation is to use Set data structure. Java has HashSet class that can be used to that end. Create two HashSets from the elements of your strings. Then, you removeAll method that is inherited from Set class.

Documentation for removeAll

HashSet documentation

An example from SO

Upvotes: 0

vibhor vaish
vibhor vaish

Reputation: 163

Gaurav a better and efficient approach would be to use linked maps instead. Put all characters of first string in the linked map with frequencies as values and characters as keys. Using this kind of map will preserve the order too.

Then traverse the second string and accordingly reduce the frequencies from the map .

You will be left with the unique characters of first string.

Complexity : Max(length of A,length of B).

Upvotes: 1

Related Questions