【刷题笔记】牛客网:删除公共字符

该代码示例是用Java编写的,主要功能是找出第一个字符串(str1)中不包含在第二个字符串(str2)中的所有字符。首先,程序遍历str2并使用HashMap存储每个字符及其出现次数。然后,遍历str1并与HashMap比较,将HashMap中不存在的字符添加到结果字符串中。最后,输出结果字符串。
摘要由CSDN通过智能技术生成

1、题目描述

在这里插入图片描述

2、题目分析

具体思路如下:
预先定义String result = ""作为输出结果
1、遍历str2字符串中的每个字符,将其存储到HashMap中(其中key为单个字符,value为该字符出现的次数)
2、遍历str1字符串中的每个字符,str1与hashmap进行比较,通过hashmap.get(字符x)如果返回的value为null,
则将此字符串加入到result输出结果中
3、输出result

3、详细代码实现

public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		String str1 = scanner.nextLine();
		String str2 = scanner.nextLine();
		String result = "";

		Map<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);
			}
		}

		for (int i = 0; i < str1.length(); i++) {
			if (map.get(str1.charAt(i)) == null) {
				result += str1.charAt(i);
			}
		}

		System.out.println(result);
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值