删除公共字符
题目描述:输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”
输入描述:每个测试输入包含2个字符串
输出描述:输出删除后的字符串
示例1
输入They are students.
aeiou
输出
Thy r stdnts.
方法1 正则表达式 替换
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String s1 = sc.nextLine();
String s2 = sc.nextLine();
String pattern = "[" + s2 + "]";
String result = s1.replaceAll(pattern, "");
System.out.println(result);
}
}
}
方法2 Hashset 法
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static String delete(String str1, String str2) {
HashSet<Character> set = new HashSet<>();//注释1
int len1 = str1.length();
int len2 = str2.length();
char[] c = new char[len1 - len2];
for (int i = 0; i < len2; i++) {
set.add(str2.charAt(i));
}
int len = 0;
for (int i = 0; i < len1; i++) {
if (!set.contains(str1.charAt(i))) {
c[len++] = str1.charAt(i);
}
}
return new String(c, 0, len);//注释2
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String src = sc.nextLine();
String del = sc.nextLine();
System.out.println(delete(src, del));
}
}
注释1. Character 不能写成char
注释2:String的其中两种构造方法
public String(char[] value)
分配一个新的 String,它表示当前字符数组参数中包含的字符序列。该字符数组的内容已被复制;后续对字符数组的修改不会影响新创建的字符串。
参数:
value - 此字符串的初始值。
public String(char[] value, int offset, int count)
分配一个新的 String,它包含来自该字符数组参数的一个子数组的字符。
offset 参数是子数组第一个字符的索引,count 参数指定子数组的长度。
参数:
- value - 作为字符源的数组。
- offset - 初始偏移量。
- count - 长度。
抛出: IndexOutOfBoundsException - 如果 offset 和 count 参数索引字符超出 value 数组的范围。
方法2’ 自制map
链接:https://www.nowcoder.com/questionTerminal/f0db4c36573d459cae44ac90b90c6212?f=discussion
来源:牛客网
import java.util.Scanner;
public class Main {
public static String delete(String src,String del){
int[] map = new int[256];
for (int i = 0; i < del.length(); i++) {
map[del.charAt(i)]++;
}
char[] ch = src.toCharArray();
int len = 0;
for (int i = 0; i < ch.length; i++) {
if(map[ch[i]] == 0){
ch[len++] = ch[i];
}
}
return new String(ch,0,len);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String src = sc.nextLine();
String del = sc.nextLine();
System.out.println(delete(src,del));
}
}