【牛客网】OR63 删除公共字符串-CSDN博客

50 阅读1分钟

在这里插入图片描述

思路

  1. 创建哈希表,将第二个字符串中出现过的字符添加到哈希表中
  2. 创建StringBuffer来拼接最后的结果字符串
  3. 遍历字符串一,如果字符在哈希表中出现过,就不拼接到字符串中,反之则拼接

Java代码

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str1 = in.nextLine();
        String str2 = in.nextLine();
        Map<Character,Integer> hashMap = new HashMap<>();
        for(int i = 0; i < str2.length(); i++){
            if(hashMap.get(str2.charAt(i)) == null ){
                hashMap.put(str2.charAt(i),1);
            }else{
                hashMap.put(str2.charAt(i) ,hashMap.get(str2.charAt(i)) + 1);
            }
        }
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < str1.length(); i++){
            if(hashMap.get(str1.charAt(i)) == null){
                sb.append(str1.charAt(i));
            }
        }        
        System.out.print(sb);
    }
}