本题来源于牛客网中,链接如下:[编程题]删除公共字符
1.题目要求
📑题目展示:
输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”
输入描述:
每个测试输入包含2个字符串
输出描述:
输出删除后的字符串
示例1:
⏩输入:
They are students.
aeiou
⏪输出:
Thy r stdnts.
2.解题思路
【题目解析】:
本题比较简单,就是两个字符串,第一个字符串是内容,第二个字符串中是想要第一个字符串消失的字符。
【解题思路】:
本题如果使用传统的暴力查找方式,如判断第一个串的字符是否在第二个串中,在再挪动字符删除这个字符的方式。同样也可以使用上hashtable数组,去判断一个字符是否在这个字符串。
📢1.直接暴力替换法
首先是第一种,也就是直接看第一个字符串,在第二个字符串有的就删除或者替换掉,那么我们可以用到两个函数,直接实现这个想法:
📍①Java substring()
方法
substring() 方法返回字符串的子字符串。
语法:
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
参数
beginIndex – 起始索引(包括), 索引从 0 开始。
endIndex – 结束索引(不包括)。
比如说:
public class Main {
public static void main(String args[]) {
String Str = new String("hi world");
System.out.print("返回值 :" );
System.out.println(Str.substring(4) );//输出 rld
System.out.print("返回值 :" );
System.out.println(Str.substring(4, 7) );//输出 rl
}
}
也就是我们可以用这个方法去拿到我们需要删除和替换的字符,用for循环直接从str2(需要删的字符的字符串)中拿去。
📍②Java replaceAll()
方法
replaceAll() 方法使用给定的参数 replacement 替换字符串所有匹配给定的正则表达式的子字符串。
简单来说就是可以用来将给定一段字符串替换掉另一段字符串。
语法:
public String replaceAll(String regex, String replacement)
参数
regex – 匹配此字符串的正则表达式。
replacement – 用来替换每个匹配项的字符串。
返回值
成功则返回替换的字符串,失败则返回原始字符串。
比如说:
public static void main(String args[]) {
String Str = new String("hello world");
System.out.print("匹配成功返回值 :" );
System.out.println(Str.replaceAll("hello", "hi" ));
//匹配成功返回值 :hi world
System.out.print("匹配失败返回值 :" );
System.out.println(Str.replaceAll("ahhhh", "hi" ));
//匹配失败返回值 :hello world
}
所以就可以直接将第二个字符串的字符内容换成""
就可以了。
📢2.使用hashtable数组
使用hash数组的其实是这样的:
- 将第二个字符串的字符都映射到一个hashtable数组中,用来判断一个字符在这个字符串。
- 判断一个字符在第二个字符串,不要使用删除,这样效率太低,因为每次删除都伴随数据挪动。这里可以考虑使用将不在字符添加到一个新字符串,最后返回新的字符串。
也就是首先,我们准备一个hash数组,设想里面是下标是ascill码表中的数,然后他们的初始值是null,我们开始先遍历第二个字符串,判断该字符在数组中是否为null,如果是的话就加1,然后再遍历第一个字符串,看见数组中为0的字符就加进新字符串中,不为零的就不用管,最后输出新字符串的值就是答案了。
比如:
3.参考代码
🚩1.直接暴力替换法
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
String str2 = sc.nextLine();
for (int i = 0; i < str2.length(); i++) {
str1 = str1.replaceAll(str2.substring(i,i+1),"");
}
System.out.println(str1);
}
🚩2.使用hashtable数组
import java.util.*;
public class Main{
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<>();
//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);
}
}
//2.遍历第一个字符串
String ret = "";
for(int i = 0;i < str1.length();i++) {
if(map.get(str1.charAt(i)) == null) {
ret += str1.charAt(i);
}
}
System.out.println(ret);
}