假定小李有
第一行输入两个正整数n,m。
接下来一行输入m个字符,每两个字符之间用空格隔开,表示小李偏爱的字符。
接下来一行输入一个字符串s。,保证题目中所有的字符均为大写字符,小李偏爱的字符互不相同,且偏爱字符至少出现一次。
输出一行字符串,表示小李将给定的字符串s替换后形成的字符串。
12 4 Z G B A ZQWEGRTBYAAI
ZZZGGGBBBAAA
字符Q为非偏爱字符,且偏爱字符Z距离它最近,所以替换成Z;同理E距离G最近,替换成G;
对于字符W,偏爱字符Z和G与其距离相同,所以替换为左边的Z;
.......
对于字符 I ,右边没有偏爱字符,左边第一个偏爱字符是A,所以替换成字符A。
同一个偏爱字符可能会在字符串中出现多次。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String mn = in.nextLine();
String cc = in.nextLine();
String s = in.nextLine();
String[] mnArr = mn.split(" ");
int n = Integer.parseInt(mnArr[0]);
List<String> cList = Arrays.asList(cc.split(" "));
char[] sArr = s.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i >= j && cList.contains("" + sArr[i - j])) {
sb.append(sArr[i - j]);
break;
}
if (i + j < n && cList.contains("" + sArr[i + j])) {
sb.append(sArr[i + j]);
break;
}
}
}
System.out.println(sb.toString());
}
} 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();
Set<character> p = new HashSet<>();
for (int i = 0; i < b; i++) {
p.add(in.next().charAt(0));
}
in.nextLine();
String s = in.nextLine();
int pre = -1;
char[] res = new char[s.length()];
for (int i = 0; i < a; i++) {
if (p.contains(s.charAt(i))) {
if (pre < 0) {
for (int j = 0; j < i; j++) {
res[j] = s.charAt(i);
}
} else {
for (int j = pre; j < (i - pre) / 2 + pre + 1; j++) {
res[j] = s.charAt(pre);
}
for (int j = (i - pre) / 2 + pre + 1; j < i; j++) {
res[j] = s.charAt(i);
}
}
res[i] = s.charAt(i);
pre = i;
}
}
if (pre > -1 && pre != a - 1) {
for (int j = pre; j < a; j++) {
res[j] = s.charAt(pre);
}
}
System.out.println(res);
}
}
} import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int n = in.nextInt(),m = in.nextInt();
String s ="";
for(int i=0;i<m;i++){
s+=in.next();
}
StringBuilder ss = new StringBuilder(in.next());
//记录所有偏爱下标:
List<Integer> list = new ArrayList<>();
for(int i =0;i<n;i++){
if(s.contains(ss.charAt(i)+"")){
list.add(i);
}
}
//遍历所有的偏爱下标,取两个下标的中点,修改,最后一个特殊:
for(int i =1;i<list.size();i++){
int l = list.get(i-1),r = list.get(i);
int mid = l+(r-l)/2;
for(int j = l+1;j<=mid;j++)ss.setCharAt(j,ss.charAt(l));
for(int j = mid+1;j<r;j++)ss.setCharAt(j,ss.charAt(r));
}
//处理第一个偏爱下标:
int index = list.get(0);
for(int i = 0;i<index;i++)ss.setCharAt(i,ss.charAt(index));
//处理最后一个偏爱下标:
index = list.get(list.size()-1);
for(int i = index+1;i<n;i++)ss.setCharAt(i,ss.charAt(index));
System.out.println(ss.toString());
}
}