题目描述
输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”
输入描述
每个测试输入包含2个字符串
输出描述
输出删除后的字符串
示例
-
输入:
-
They are students.
aeiou
输出
-
Thy r stdnts.
思想方法
用哈希表对问题进行求解
- 将第二个字符串的字符都映射到一个hashtable数组中,用来判断一个字符在这个字符串;
- 将该数组与第一个字符进行比较,将第二个字符串中不存在的字符放到新的一个字符串中,最后返回新的字符串。
代码解析:
Scanner sc = new Scanner(System.in);
//用的是nextline(),如果用next()的话取到空格就停止了
String str1 = sc.nextLine();
String str2 = sc.nextLine();
//构建一个键为字符类型,值为Integer类型的HashMap
HashMap<Character,Integer> map = new HashMap<>();
先对第二个字符串进行遍历,如果所对应的HahMap值为空(Integer类型==null),就将其值设为1,代表这个值出现一次,如果不为空就在原来的值的基础上+1,则该值出现多次。
for(int i =0;i<str2.length();i++){
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);
}
}
再对第一个字符串进行遍历找到与第二个字符串中不符合的字符未出现的字符。
(即代表该字符在HashMap中所对应的值为0)
String s = "";
for(int i =0;i<str1.length();i++){
if(map.get(str1.charAt(i))==null){
s += str1.charAt(i);
}
}
System.out.println(s);
最终输出新的字符串s。
完整代码:
import java.util.HashMap;
import java.util.Scanner;
public class deleteCharInString {
//输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。
// 例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
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.put(str2.charAt(i),1);
}else{
map.put(str2.charAt(i),map.get(str2.charAt(i))+1);
}
}
String s = "";
for(int i =0;i<str1.length();i++){
if(map.get(str1.charAt(i))==null){
s += str1.charAt(i);
}
}
System.out.println(s);
}
}