【算法刷题记录(简单题)002】字符串字符匹配(java代码实现)

发布于:2025-07-06 ⋅ 阅读:(22) ⋅ 点赞:(0)

一、题目描述

对于给定的字符串 s 和 t ,检查 s 中的所有字符是否都在 t 中出现。

(一)输入描述

第一行输入一个长度为 1 ≤ len(s) ≤ 200、仅由小写字母组成的字符串 s。
第二行输入一个长度为 1 ≤ len(t) ≤ 200、 仅由小写字母组成的字符串 t。

(二)输出描述

如果 s 中的所有字符都在 t 中出现,则输出 true,否则输出 false。

(三)示例

输入:bc
     abc
输出:true

二、题目解答

(一)解题思路

1.使用HashMap统计字符串 s 中字符,如字符 a 出现则利用put方法将键值对(a,1)存入 map 中(注:a 重复出现存入的 value 值仍为1)。
2.使用HashMap的 put 方法统计 t 中的字符是否在 s 中出现,假设字符 a 在 t 中 出现,则将键值对(a,map.getOrDefault(a, 0))存入。
3.遍历 map.value() ,如存在为1的 value ,则代表 s 中存在 t 中没有的字符,则输出 f ,否则输出 t。

(二)代码实现

import java.util.*;
public class Main {
	public static void main(String[] args){
		//读取字符串S和t
		Scanner in = new Scanner(System.in);
		String s = null;
		String t = null;
		
		s = in.nextLine();
		t = in.nextLine();
		
		//将s中的字符存入HashMap中
		Map<Character,Integer> map = new HashMap<>();
		for(Character c : s.toCharArray()){
			map.put(c, 1);
		}
		//统计t中的字符是否在s中出现
		for(Character c : t.toCharArray()){
			map.put(c, map.getOrDefault(c, 0)-1);
		}
		//遍历HashMap.value(), 如存在1则表明s中存在t中没有的字符
		for(int a : map.values()){
			if(a == 1){
				System.out.print("false");
				System.exit(0);//此处不能使用break;因为break只会终止循环,不会终止程序。
			}
		}
		System.out.print("true");
	}
}