牛客华为算法-HJ81 字符串字符匹配

我爱海鲸 2025-04-22 12:48:36 暂无标签

简介华为od

字符串字符匹配_牛客题霸_牛客网

描述

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

输入描述:

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

输出描述:

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

解法一:(java)

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // while (in.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
        String s = in.nextLine();
        String t = in.nextLine();
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();

        for (int i = 0 ; i < s.length() ; i++) {
            int c = s.charAt(i);
            set1.add(c);
        }

        for (int i = 0 ; i < t.length() ; i++) {
            int c = t.charAt(i);
            set2.add(c);
        }

        boolean bool = set2.containsAll(set1);

        System.out.println(bool);

    }
}

思路:将两个字符串分别遍历放到两个不同的set集合中,然后看第二个集合是否包含第一个集合即可。

你好:我的2025