从字符串中删除字符所需的建议

时间:2019-06-19 17:22:46

标签: java

我编写了一个程序,从第二个字符串中删除第一个字符串中存在的字符。

我已经为上述问题编写了代码,有人可以建议更改以使其高效

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);
  }
}

输出为:Grv

2 个答案:

答案 0 :(得分:1)

Gaurav更好,更有效的方法是改为使用链接地图。 将第一个字符串的所有字符放入链接的映射中,频率作为值,字符作为键。 使用这种地图也会保留顺序。

然后遍历第二个字符串,并相应地降低地图的频率。

您将获得第一个字符串的唯一字符。

复杂度:最大值(A的长度,B的长度)。

答案 1 :(得分:0)

这种类型的列表差异操作在计算机科学中的一般经验法则是使用Set数据结构。 Java具有可用于此目的的HashSet类。从字符串的元素创建两个HashSet。然后,从Set类继承的removeAll方法。

Documentation for removeAll

HashSet documentation

An example from SO