import java.util.Scanner; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { // 创建扫描器对象,用于读取输入数据 Scanner in = new Scanner(System.in); // 循环处理多组测试用例(当输入中存在下一个整数时继续) while (in.hasNextInt()) { // 读取n:字符串需要处理的长度(题目中的n) int a = in.nextInt(); // 读取m:偏爱字符的数量(题目中的m) int b = in.nextInt(); // 创建集合存储所有偏爱字符,利用HashSet实现O(1)时间复杂度的包含判断 Set<Character> preferredChars = new HashSet<>(); // 循环读取m个偏爱字符并添加到集合中 for (int i = 0; i < b; i++) { // 读取输入的字符串并取第一个字符(因为输入的是单个字符,用空格分隔) preferredChars.add(in.next().charAt(0)); } // 消耗掉输入缓冲区中残留的换行符,避免影响后续nextLine()读取完整字符串 in.nextLine(); // 读取原始字符串s String s = in.nextLine(); // 记录上一个偏爱字符在字符串中的位置,初始值-1表示尚未找到任何偏爱字符 int lastPreferredIndex = -1; // 创建结果字符数组,长度与原始字符串一致,用于存储替换后的结果 char[] result = new char[s.length()]; // 遍历字符串的前a个字符(题目要求处理的长度) for (int currentIndex = 0; currentIndex < a; currentIndex++) { // 判断当前位置的字符是否为偏爱字符 if (preferredChars.contains(s.charAt(currentIndex))) { // 情况1:第一次遇到偏爱字符(之前没有记录过偏爱字符位置) if (lastPreferredIndex < 0) { // 将从字符串开头到当前偏爱字符位置前的所有字符 // 替换为当前偏爱字符(因为左侧没有其他偏爱字符) for (int j = 0; j < currentIndex; j++) { result[j] = s.charAt(currentIndex); } } else { // 情况2:不是第一次遇到偏爱字符,处理两个偏爱字符之间的区域 // 计算中间位置,用于划分两个偏爱字符的影响范围 // 公式含义:两位置间距的一半向上取整,加上前偏爱字符位置 int midPosition = (currentIndex - lastPreferredIndex) / 2 + lastPreferredIndex + 1; // 中间位置左侧(包含lastPreferredIndex,不包含midPosition) // 替换为上一个偏爱字符(距离更近或相同距离时选左侧) for (int j = lastPreferredIndex; j < midPosition; j++) { result[j] = s.charAt(lastPreferredIndex); } // 中间位置及右侧(包含midPosition,不包含currentIndex) // 替换为当前偏爱字符(距离更近) for (int j = midPosition; j < currentIndex; j++) { result[j] = s.charAt(currentIndex); } } // 当前位置是偏爱字符,直接保留该字符到结果中 result[currentIndex] = s.charAt(currentIndex); // 更新上一个偏爱字符的位置为当前位置 lastPreferredIndex = currentIndex; } } // 处理最后一个偏爱字符右侧的区域(如果存在) // 条件:存在偏爱字符(lastPreferredIndex > -1),且最后一个偏爱字符不在字符串末尾 if (lastPreferredIndex > -1 && lastPreferredIndex != a - 1) { // 将从最后一个偏爱字符位置到字符串末尾(前a个字符内)的所有字符 // 替换为最后一个偏爱字符(因为右侧没有其他偏爱字符) for (int j = lastPreferredIndex; j < a; j++) { result[j] = s.charAt(lastPreferredIndex); } } // 将结果字符数组转换为字符串并输出 System.out.println(result); } // 关闭扫描器,释放资源 in.close(); } }