Java编程题:删除公共字符

删除公共字符

输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”

输入描述:
每个测试输入包含2个字符串

输出描述:
输出删除后的字符串

输入
They are students.
aeiou
输出
Thy r stdnts.

方法1:

import java.util.*;
public class Main{
	public static void function(String f,String l){
		char[] array = f.toCharArray();
		for(int i=0;i<array.length;i++){
			String ch =array[i]+"";
			if(!l.contains(ch)){
				System.out.print(ch);
			}
		}
	}
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()){
		String first = sc.nextLine();
		String last = sc.nextLine();
		function(first,last);
	}
}
}

方法2:

import java.util.*;
public class Main {
	public static String DeleteChars(String str1,String str2) {
		if(str1==null || str2==null){
			return null;
		}
		//数组大小为256,因为字符最多256个
		boolean[] hashTable = new boolean[256];
		int lenStr2 = str2.length();
		int i = 0;
		//将str2中字符对应的hashtable数组中的位置上的值设为ture
		while(i < lenStr2){
			int index = str2.charAt(i);
			hashTable[index] = true;
			i++;
		}
		char[] str1s = str1.toCharArray();
		int k = 0;
		int j = 0;
		//开始遍历str1,寻找在str2中没有出现过的字符,
		//从str1s的前面依次进行覆盖
		while(k < str1s.length) {
			int index = str1s[k];
			if(!hashTable[index]){
				str1s[j++] = str1s[k];
			}
			k++;
		}
	//不进行重新拷贝的话,打印果会包含原有的部分数据。
	str1s = Arrays.copyOf(str1s,j);
	return String.copyValueOf(str1s);
	}
	
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	while (sc.hasNext()) {
		String s1 = sc.nextLine();
		String s2 = sc.nextLine();
		String str = DeleteChars(s1,s2);
		System.out.println(str);
	}
}
}

注意:
数组大小为256,因为字符最多256个,boolean[] hashTable = new boolean[256];

来源:牛客网

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值