一、题目描述
输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”
二、输入输出和示例
输入描述:
每个测试输入包含2个字符串
输出描述:
输出删除后的字符串
示例1
输入
They are students.
aeiou
输出
Thy r stdnts.
三、思路分析
使用hashMap,遍历第二个字符串,将每一个字符作为key,如果当前map中没有这个key,那value就为1,如果有这个key,那value就+1。然后遍历第一个字符串,如果在map中有key相等的字符,就不管,把不相等的拼接起来输出,完成要求。
四、代码
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String str1 = sc.nextLine();
String str2 = sc.nextLine();
HashMap<Character, Integer> map = new HashMap<>();
for(int i = 0; i < str2.length(); i++){//遍历第二个字符串
if(map.get(str2.charAt(i)) == null){//如果当前map中没有这个字符,就把这个字符作为key插入,并且将value改成1
map.put(str2.charAt(i), 1);
}else{//如果map中有这个字符,就把当前这个字符当做key加入,value再+1
map.put(str2.charAt(i), map.get(str2.charAt(i) + 1));
}
}
String ret = "";
for(int i = 0; i < str1.length(); i++){//遍历第一个字符串
if(map.get(str1.charAt(i)) == null){//如果当前map中没有和字符一样的,就拼接起来,最后输出
ret += str1.charAt(i);
}
}
System.out.println(ret);
}
}
}