题目描述:
链接:https://www.nowcoder.com/questionTerminal/f88dafac00c8431fa363cd85a37c2d5e
输入描述:
输入在2行中分别给出应该输入的文字、以及实际被输入的文字。每段文字是不超过80个字符的串,由字母A-Z(包括大、小写)、数字0-9、
以及下划线“_”(代表空格)组成。题目保证2个字符串均非空。
输出描述:
按照发现顺序,在一行中输出坏掉的键。其中英文字母只输出大写,每个坏键只输出一次。题目保证至少有1个坏键。
示例:
输入:
7_This_is_a_test
_hs_s_a_es
输出:7TI
求解思路:
- 预期打印字符串 except 和 实际打印字符串 actual,将所有字符均转为大写字符;
- 将字符串 actual 存入 Set 中;
- 遍历字符串 except ,将其与 Set 对比,若 Set 中存在,则跳过此正常键;未出现,则将此坏键插入 brokenSet 中,(插入之前需判断此键在 brokenSet 中是否已存在,存在则跳过,不存在则插入)。
代码实现:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String expect = scanner.next();
String actual = scanner.next();
//转为题目要求的大写字母
expect = expect.toUpperCase();
actual = actual.toUpperCase();
//将actual存入set
Set<Character> actualSet = new HashSet<>();
for(int i = 0;i < actual.length();i++){
actualSet.add(actual.charAt(i));
}
//遍历except,将actual中没有的字符添加至坏键的set中
Set<Character> brokenSet = new HashSet<>();
for(int i = 0;i < expect.length();i++){
char c = expect.charAt(i);
if(actualSet.contains(c)){
continue;
}
if(brokenSet.contains(c)){
continue;
}else{
System.out.print(c);
brokenSet.add(c);
}
}
}
System.out.println();
}
}