旧键盘题(20)HashSet

链接:https://www.nowcoder.com/questionTerminal/f88dafac00c8431fa363cd85a37c2d5e?toCommentId=11304188
来源:牛客网
旧键盘题(20)
链接:https://www.nowcoder.com/questionTerminal/f88dafac00c8431fa363cd85a37c2d5e
来源:牛客网
旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现。现在给出应该输入的一段文字、以及实际被输入的文字,请你列出
肯定坏掉的那些键。

输入描述:
输入在2行中分别给出应该输入的文字、以及实际被输入的文字。每段文字是不超过80个字符的串,由字母A-Z(包括大、小写)、数字0-9、
以及下划线“_”(代表空格)组成。题目保证2个字符串均非空。


输出描述:
按照发现顺序,在一行中输出坏掉的键。其中英文字母只输出大写,每个坏键只输出一次。题目保证至少有1个坏键。

我的思路:
链接:https://www.nowcoder.com/questionTerminal/f88dafac00c8431fa363cd85a37c2d5e
来源:牛客网

import java.util.*;
public class Main{
    public static void func(String str1,String str2){
        HashSet<Character> set = new HashSet<>();
        HashSet<Character> get = new HashSet<>();
        for (char ch : str2.toUpperCase().toCharArray()) {
            set.add(ch);
        }
        for (char ch : str1.toUpperCase().toCharArray()){
            if (!set.contains(ch) && !get.contains(ch)){
                get.add(ch);
                System.out.print(ch);
            }
        }
    }
    
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        while (scan.hasNextLine()) {
            String str1 = scan.nextLine();
            String str2 = scan.nextLine();
            func(str1,str2);
        }
    }
}

建立两个HashSet,第一个存放坏键盘打出来的字符串str2,第二个存放应该打出来的字符串str1,把str2扔进第一个HashSet里面(注意所有的字符串都应该更改为大写),再遍历str1,用HashSet判断是否包含str1里面的按键,不包含的就是坏掉的按键,把坏掉的按键都扔进另一个HashSet里面,洗掉重复的字母。
总结就是第一个HashSet用来找到坏键并扔到第二个HashSet里面,然后第二个HashSet洗掉重复的字符就出炉啦

#笔经#
全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务