题目描述
输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”
输入描述:
每个测试输入包含2个字符串
输出描述:
输出删除后的字符串
示例1
输入
They are students.
aeiou
输出
Thy r stdnts.
解题思路
首先创建两个字符串str1、str2,创建HashMap<Character,Interger>用于存放字符及其对应的次数,初始字符值为null,第一步遍历第二个字符串,判断拿到的字符是否存在于map中,如果拿到的字符为null,则放入map中并对应次数为1次,如果拿到的字符不为null,则再让该字符的次数加1,第二步遍历第一个字符串,在map中找到对应字符,如果该字符为null,即输出到新字符串ret中,最后打印字符串ret。
实现代码
import java.util.*;
public class Main{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String str1 = scan.nextLine();
//They are students.
String str2 = scan.nextLine();
//aeiou
HashMap<Character,Integer> map = new HashMap<>();
//1、遍历第二的字符串
for(int i = 0;i < str2.length();i++) {
// 当前拿到的字符判断之前是否存在于map当中
if(map.get(str2.charAt(i)) == null) {
map.put(str2.charAt(i), 1);
}else {
map.put(str2.charAt(i), map.get(str2.charAt(i))+1);
}
}
String ret = "";//最后输出的字符串
//2、遍历第一个字符串
for(int i = 0;i < str1.length();i++) {
// 当第一个字符串中相对应的字符为空时,即可输出该字符
if(map.get(str1.charAt(i))== null) {
ret += str1.charAt(i);
}
}
System.out.println(ret);
}
}